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
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With