I develop both android(Java) and IOS(swift) applications. I had a problem on the Android side and I solved it.I’m having the same problem on the IOS side but I couldn’t solve it.
I have a tableview in my application and I fill it with data I get from my own server.
However, when I swipe through the list, sometimes the values and images in the list item get mixed up between the list items.
This little code on the Android side solved my problem
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
return position;
}
I searched for override methods but I couldn’t find an equivalent event that would solve my problem.
The list interface is like this, a simple list.
Maybe there is a problem with uploading the images, I upload it like this
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "mainCell", for: indexPath) as! MainTableCell
let item = radio_type_list[indexPath.row]
cell.RadioTitle.text = item.title
cell.RadioDescription.text = item.desc
cell.RadioImage.downloadImageFrom(link:item.imageurl, contentMode: UIView.ContentMode.scaleToFill)
return cell;
}
let imageCache = NSCache<NSString, AnyObject>()
extension UIImageView {
func downloadImageFrom(link:String, contentMode: UIView.ContentMode) {
let imageCache = NSCache<NSString, AnyObject>()
if let cachedImage = imageCache.object(forKey: (link as AnyObject) as! NSString) {
self.image = cachedImage as? UIImage
self.contentMode = .scaleAspectFill
return
}
URLSession.shared.dataTask( with: NSURL(string:link)! as URL, completionHandler: {
(data, response, error) -> Void in
DispatchQueue.main.async {
self.contentMode = contentMode
if let data = data { self.image = UIImage(data: data) }
}
}).resume()
}
}
2
Answers
The issue you’re experiencing occurs because the images get mixed up or swapped between cells as they scroll in and out of view
You can learn more about
dequeue mechanisim
of ios following this linkSo when you scroll through your list, whenever a cell get dequeue, you start a
download image task
from anUIImageView
. The problem arise when cell got reuse, there is a chance the olddownload task
take longer time than the newdownload task
one for that cell. Here is my suggestion code to fix your problem: