简体   繁体   中英

Tableview reusing the cells and showing wrong data first

Hello I've been having this problem for awhile. I want to stop the tableview from reusing the cell. It keeps displaying the wrong information when i scroll then it shows the right thing like a few milliseconds. How can i stop the tableview from reusing the cell or how can i reuse the cell and make it not do that.

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return cats.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellIdentifier = "CategoryTableViewCell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! CategoryTableViewCell
    cell.nameLabel.text = cats[indexPath.row].categoryName
    cell.subNameLabel.text = cats[indexPath.row].appShortDesc
    let catImageUrl = cats[indexPath.row].imageUrl
            let url = NSURL(string: "https:\(catImageUrl)")
            let urlRequest = NSURLRequest(URL: url!)
            NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
                if error != nil {
                    print(error)
                } else {
                    if let ass = UIImage(data: data!) {
                            cell.photoImageView.image = ass
                        }
                    self.loading.stopAnimating()
                }
            }
    return cell
}

The problem is that you are seeing an image from a previous cell. Simply initialize the image to nil when you dequeue the reused cell:

cell.photoImageView.image = nil

or set it to a default image of your choosing.


Note, the way you are updating the image after it loads has issues.

  1. The row may no longer be on screen when the image finally loads, so you will be updating a cell that has been reused itself.

  2. The update should be done on the main thread.

A better way to do this would be to have an array that caches the images for the cells. Load the image into the array, and then tell the tableView to reload that row.

Something like this:

dispatch_async(dispatch_get_main_queue()) {
    self.imageCache[row] = ass
    self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: row, inSection: 0)],
        withRowAnimation: .None)
}

override prepareForReuse() method in your cell class and reset your values

 override func prepareForReuse() {
        super.prepareForReuse()
        nameLabel.text = ""
    }

This method is called every time the UITableView before reuses this cell

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM