IOS - SWIFT - CollectionView With images, loading

2019-06-04 02:52发布

问题:

I have a collection view and array with URLs of different images. and when i launch the app, collection view starts to load images through the array:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CellView

    var url = arr[indexPath.row]

    var urls = NSURL(string: url)
    var data = NSData(contentsOfURL: urls!)

    cell.ImageView.image = UIImage(data: data!)

    return cell
}

and the trouble appearse: for example on 4th cell collection view loading all 4 urls for all 4 cells and it takest alot time. how can collection view load particular url for particular cell and don't spend time to load urls to cells that already loaded?

Thanks for any help!!

回答1:

I suggest using a third party library for this matter, it called SDWebImage.

And than for each image view inside a cell set:

self.imageView.sd_setImageWithURL(url, completed: block)


回答2:

Or you can use similar third party library, as Asaf, told you. I used to use HANEKE for DL/cache images.

Take a look: https://github.com/Haneke/HanekeSwift

:)