SDWebImage does not load remote images until scroll

前端 未结 4 2065
清歌不尽
清歌不尽 2020-12-13 07:39

I am using SDWebImage library to load remote images into a table view which uses a custom cell class i have created. I simply use

[cell.imageView setImageWit         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-13 08:14

    This is an example and you need to implement this for your purpose.
    your UITableView delegate:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        YourCustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YourCustomTableViewCellReuseIdentifier"];
    
        if (!cell)
        {
            cell = [[[YourCustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                   reuseIdentifier:CellIdentifier];        
        }
    
        NSString *imageURL = // ... get image url, typically from array
        [cell loadImageWithURLString:imageURL forIndexPath:indexPath]; 
    
        return cell;
    }
    

    your custom UITableViewCell .h file:

    #import 
    #import "UIImageView+WebCache.h"
    #import "SDImageCache.h"
    
    @interface YourCustomTableViewCell
    {
        NSIndexPath *currentLoadingIndexPath;
    }
    
    - (void)loadImageWithURLString:(NSString *)urlString forIndexPath:(NSIndexPath *)indexPath;
    
    @end
    

    your custom UITableViewCell .m file:

    // ... some other methods
    
    - (void)loadImageWithURLString:(NSString *)urlString forIndexPath:(NSIndexPath *)indexPath
    {
        currentLoadingIndexPath = indexPath;
        [self.imageView cancelCurrentImageLoad];
        [self.imageView setImage:nil];
    
        NSURL *imageURL = [NSURL URLWithString:urlString];
        [self.imageView setImageWithURL:imageURL
                       placeholderImage:nil
                                options:SDWebImageRetryFailed
                              completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
        {
            if (currentLoadingIndexPath != indexPath)
            {
                return;
            }
    
            if (error)
            {
                ... // handle error
            }
            else
            {
                [imageView setImage:image];
            }
        }];
    }
    
    // ... some other methods
    

    currentLoadingIndexPath needed to detect if we reuse this cell for another image instead of image which was downloaded while user scrolls the table view.

提交回复
热议问题