UICollectionView - Downloading images and effective reloading of data, like Instagram

后端 未结 3 1051
梦谈多话
梦谈多话 2021-02-01 08:24

I noticed that apps like Intagram uses UICollectionViews to display the feed of photos. I also noticed that the cells for these photos is somehow placed on screen

3条回答
  •  Happy的楠姐
    2021-02-01 08:54

    Use following to load image Async in cell in cellForItemAtIndexPath delegate method

    let url = URL(string: productModel.productImage)
    
        let data = try? Data(contentsOf: url!)
        DispatchQueue.main.async(execute: {
            collectionViewCell.imageView.image = UIImage(data: data!)
        });
    

    Implement protocol "UICollectionViewDataSourcePrefetching" in you ViewController as

    class ViewController: UIViewController , UICollectionViewDataSourcePrefetching {

    Set following delegates to your collection view in storyboard (see the attached image) or programmatically

    In ViewController's viewDidLoad method

    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.prefetchDataSource = self
    

提交回复
热议问题