To cancel a cell drawing during UITableview that no longer needs to be displayed

Asked 2 years ago, Updated 2 years ago, 62 views

Swift programming using Xcode 7.3.

 functableView(table:UITableView, cellForRowAtIndexPath:NSIndexPath)->UITableViewCell{
    letcell=table.dueReusableCellWithIdentifier("Cell") as? CustomTableViewCell

        let url —NSURL = NSURL (string: (fileArray [indexPath.row] as ? US>String)!+ ".jpg")!
        let req = NSURLRequest (URL: url)
        NSURLConnection.sendAsynchronousRequest(requ,queue:NSOperationQueue.mainQueue()) {(res,data,err)in
            let img = UIImage (data:data!)
            cell!.thumb.image=img
        }

As shown in , the image (cell.thumb.image) is displayed in the cell, but if you scroll fast, the image cannot be read and displayed, and the thumbnail flaps when it stops.

Would it be possible to read images that do not need to be displayed or cancel the display?

swift uitableview

2022-09-30 10:18

1 Answers

NSURLConnection.sendAsynchronousRequest() does not support cancellation processing.NSURLConnection also has a cancelable API, but NSURLConnection is deprecated from iOS 9, so use a new one, such as NSURLSession or library.

To download the image, create the NSURLSessionDataTask from NSURLSession.Keep the NSURLSessionDataTask so that you can cancel it later if the cell is hidden (off-screen).

In the example below, we use the dictionary downloadTasksPerURL to keep the URL as a key.
Also, we have cells have the URL of the image so that they can identify the NSURLSessionDataTask to cancel when the cell is hidden.

When a cell exits the screen, the tableView(_:didEndDisplayingCell:forRowAtIndexPath:) delivery method is called, so cancel the appropriate NSURLSessionDataTask with the cancel() method at that time.

Below is an example code.

...
var downloadTasksPerURL = NSURLSessionTask()
...

functableView(table:UITableView, cellForRowAtIndexPathindexPath:NSIndexPath) ->UITableViewCell{
    ...
    let imageURL=...

    let task = NSURLSession.sharedSession().dataTaskWithRequest (NSURLRRequest (URL: imageURL)) {(data, response, error) ->Void in
        iflet error = error {
            return
        }

        dispatch_async(dispatch_get_main_queue()) {
            let image=UIImage(data:data!)!
            cell!.thumb.image=image
        }
    }

    cell.imageURL=imageURL
    downloadTasksPerURL [imageURL] = task

    task.resume()

    return cell
}

functableView (tableView: UITableView, didEndDisplayingCell: UITableViewCell, forRowAtIndexPath indexPath:NSIndexPath) {
    iflet task=downloadTasksPerURL [cell.imageURL] {
        task.cancel()
    }
}


2022-09-30 10:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.