swiftuicollectionviewrealmhaneke

Image in cell doesn't appear in search result


I have collection view and have 7 cell. When app running, it display 6 and must scroll to view the 7th cell. Each cell has an image but the 7th cell image didn't show until I scroll and view the 7th cell. It make if i search the 7th cell, the image from 7th cell doesn't appear instead using the 6th cell image, after short moment it display the original image. Looks like it's still loading but how to make image in 7th after search not using the 6th cell image.

I use realm to store image url and haneke to show image

private var database = [Magazine]()

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let magazineObject = database[indexPath.item]
    let imageUrl:NSURL = NSURL(string: magazineObject.image)!
     cell.displayImage.hnk_setImageFromURL(imageUrl, placeholder: nil, success: { (image) -> Void in
        cell.displayImage.image = image
        cell.activityIndicator.hidden = true
        cell.activityIndicator.stopAnimating()
        }, failure: { (error) -> Void in

    })
return cell
}

my Magazine class looks like this

import Foundation
import RealmSwift

class Magazine: Object { 
    dynamic var id = 0
    dynamic var pathDatabase = ""
    dynamic var image = ""
    dynamic var urlMagazine = ""
    dynamic var title = ""
    dynamic var progressBarDownload = 0
    dynamic var progressBarTitle = ""
    dynamic var statusDownload = 0
}

Solution

  • For new visible cell, collectionview reuse object of cell which created but not displaying. so in your cellforitem method, you should initialise all uielements.

    add following in your code

    cell.displayImage.image = nil; //or assign placeholder image if you have here.

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let magazineObject = database[indexPath.item]
    
        cell.displayImage.image = nil; //or assign placeholder image if you have here.
    
        let imageUrl:NSURL = NSURL(string: magazineObject.image)!
        cell.displayImage.hnk_setImageFromURL(imageUrl, placeholder: nil, success: { (image) -> Void in
            cell.displayImage.image = image
            cell.activityIndicator.hidden = true
            cell.activityIndicator.stopAnimating()
        }, failure: { (error) -> Void in
    
        })
        return cell
    }