loading image in UITableViewCell asynchronously

前端 未结 2 2121
旧时难觅i
旧时难觅i 2021-02-11 07:52

What is the super very easy way to load the image in the UITableViewCell asynchronously say given a imageURL without having to subclassing the UITableViewCell, i.e: standard UIT

相关标签:
2条回答
  • 2021-02-11 08:19

    The easiest way I know is to use SDWebImage library. Here is a link that explains how to utilize the SDWebImage library to load avatars asynchronously.

    SDWebImage is an extension to the ImageView. Here is the usage:

    // load the avatar using SDWebImage
        [cell.imageView setImageWithURL:[NSURL URLWithString:tweet.profileImageUrl]
                       placeholderImage:[UIImage imageNamed:@"grad_001.png"]];
    

    And here is the referenced article:

    Implementing Twitter Search

    0 讨论(0)
  • 2021-02-11 08:32

    In your .m, include the objective c runtime:

    #import <objc/runtime.h>
    

    At the top of your @implementation section, define a static constant for use below:

    static char * const myIndexPathAssociationKey = "";
    

    In your cellForRowAtIndexPath, add the following code:

    // Store a reference to the current cell that will enable the image to be associated with the correct  
    // cell, when the image subsequently loaded asynchronously. Without this, the image may be mis-applied
    // to a cell that has been dequeued and reused for other content, during rapid scrolling. 
    objc_setAssociatedObject(cell,
                             myIndexPathAssociationKey,
                             indexPath,
                             OBJC_ASSOCIATION_RETAIN);
    
    // Load the image on a high priority background queue using Grand Central Dispatch.
    // Can change priority by replacing HIGH with DEFAULT or LOW if desired.
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    dispatch_async(queue, ^{
        UIImage *image = ... // Obtain your image here.
    
        // Code to actually update the cell once the image is obtained must be run on the main queue.
        dispatch_async(dispatch_get_main_queue(), ^{
            NSIndexPath *cellIndexPath = (NSIndexPath *)objc_getAssociatedObject(cell, myIndexPathAssociationKey);
            if ([indexPath isEqual:cellIndexPath]) {
            // Only set cell image if the cell currently being displayed is the one that actually required this image.
            // Prevents reused cells from receiving images back from rendering that were requested for that cell in a previous life.
                [cell setImage:image];
            }
        });
    }];
    

    Finally, for supporting best performance when rapidly scrolling on older devices you may want to load the most recently requested images first... for that, see this thread for asynchronously loading cell images using a last-in first-out stack and GCD.

    0 讨论(0)
提交回复
热议问题