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

后端 未结 3 1010
梦谈多话
梦谈多话 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条回答
  • 2021-02-01 08:50

    use

    [self.collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];

    instead of

    [self.collectionView reloadData];

    here indexPath is the NSIndexPath Object for the corresponding UICollectionViewCell Object

    0 讨论(0)
  • 2021-02-01 08:53

    The technique you want to implement is called lazy loading. Since you are using AFNetworking it will be easier to implement this in your case. Each of your collection view cell needs to have a UIImageView to display the image. Use the UIImageView+AFNetworking.h category and set the correct image URL by calling method

    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        // ....
    
        [cell.imageView setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    
        // ...
        return cell;
    }
    

    Placeholder is the image which will be displayed until required image is downloaded. This will simply do the required job for you.

    Note: By default, URL requests have a cache policy of NSURLCacheStorageAllowed and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use setImageWithURLRequest:placeholderImage:success:failure:.

    Also, for you reference, if you want to implement lazy loading of images yourself, follow this Apple sample code. This is for UITableView but same technique can be used for UICollectionView as well.

    Hope that helps!

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题