Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusable Cell isn't calling prepareForReuse function

Ok, need a little help here. I'm new to Swift. Here's my issue.

When getting data for my UITableView, I'm calling image data from a url, so there is a slight delay when grabbing reused cells, resulting in the cell showing old data for half a second. I've tried to call func prepareForReuse to reset properties, but it doesn't seem to be working. Any help is appreciated!

Here's my code when calling cell:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    cell.alpha = 0
    let book = books[indexPath.row]
    cell.textLabel?.text = book.bookTitle
    cell.detailTextLabel?.text = book.postURL
    let url = URL(string: book.postPicture)
    DispatchQueue.global().async {
        let data = try? Data(contentsOf: url!)
        DispatchQueue.main.async {
            cell.alpha = 0
            cell.backgroundView = UIImageView(image: UIImage(data: data!))
            UIView.animate(withDuration: 0.5, animations: {
                cell.alpha = 1
            })
        }
    }
    cell.contentView.backgroundColor = UIColor.clear
    cell.textLabel?.backgroundColor = cell.contentView.backgroundColor;
    cell.detailTextLabel?.backgroundColor = cell.contentView.backgroundColor;

    func prepareForReuse(){
        cell.alpha = 0
        cell.backgroundView = UIImageView(image: UIImage(named: "book.jpg"))
    }
    return cell


}
like image 957
Gerrit Avatar asked Feb 05 '23 20:02

Gerrit


1 Answers

You should subclass UITableView cell and inside your custom class override:

import UIKit

class CustomTableViewCell: UITableViewCell {

    override func prepareForReuse() {
        // your cleanup code
    }
}

then in UITableViewDataSource method reuse the custom cell:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: CustomTableViewCell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! CustomTableViewCell
    return cell
}
like image 95
Oleh Zayats Avatar answered Feb 07 '23 18:02

Oleh Zayats