UICollectionView reloads wrong images on scroll

后端 未结 3 2063
天命终不由人
天命终不由人 2021-02-14 11:46

In the code below, I download image URLs from a text file, store it in a NSMutableArray, then download the images from from those URLS in CellforItemAtIndexPath. However, when I

3条回答
  •  不知归路
    2021-02-14 12:21

    I'm not sure what AsyncImageView is, so first let me answer your question as if it were a UIImageView:


    In your callback block (when you go back to the main queue), you are referring to recipeImageView. However, if the user has scrolled during download, the cell object has been reused.

    Once you're in the callback, you have to assume that all of your references to views (cell, recipeImageView, blurView, etc. are pointing to the wrong thing. You need to find the correct views using your data model.

    One common approach is using the NSIndexPath to find the cell:

    UICollectionViewCell *correctCell = [collectionView cellForItemAtIndexPath:indexPath]:
    UIImageView *correctRecipeImageView = (UIImageView *)[correctCell viewWithTag:100];
    /* Update your image now… */
    

    Note that this will only work if one indexPath is always guaranteed to point at the same content - if the user can insert/delete rows, then you'll need to figure out the correct indexPath too, since it may have changed as well:

    NSIndexPath *correctIndexPath  = /* Use your data model to find the correct index path */
    UICollectionViewCell *correctCell = [collectionView cellForItemAtIndexPath:correctIndexPath]:
    UIImageView *correctRecipeImageView = (UIImageView *)[correctCell viewWithTag:100];
    /* Update your image now… */
    

    That said, if AsyncImageView is some other class that's supposed to handle all of this for you, then you can just call setImageWithURL: placeholderImage: on the main thread, and it should handle all the asynchronous loading on your behalf. If it doesn't, I'd like to recommend the SDWebImage library, which does: https://github.com/rs/SDWebImage

提交回复
热议问题