簡體   English   中英

從AFNetworking下載設置TableView單元格圖像

[英]Set TableView Cell image from AFNetworking download

我正在使用AFNetworking將rss feed圖像集下載到表視圖。 以下是我正在使用的代碼。

- (UITableViewCell *)tableView:(UITableview *)tableView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    Cell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"MY_CELL" forIndexPath:indexPath];

    NSString *wallpaperLink = [af setThumbString:[[feeds objectAtIndex:indexPath.row] objectForKey: @"wallpaper"]];

    //AfNetwork Download
    AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:wallpaperLink]]];
    requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
       //Set Cell Image from response
       cell.imageView.image = responseObject;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Image error: %@", error);
    }];
    [requestOperation start];

    return cell;
}

但是當我瀏覽一些教程時,我意識到這不是使用AFNetworking下載異步圖像的方法。 有人能告訴我我的代碼,如何下載並將responseobject添加到cell.imageView.image ???

我這樣做是為了避免內存泄漏:

NSURL *url = [NSURL URLWithString:@"http:url..."];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
UIImage *placeholderImage = [UIImage imageNamed:@"your_placeholder"];

__weak UITableViewCell *weakCell = cell;

[cell.imageView setImageWithURLRequest:request
                      placeholderImage:placeholderImage
                               success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

                                   weakCell.imageView.image = image;
                                   [weakCell setNeedsLayout];

                               } failure:nil];

它適用於AFNetworking 2。

正如@Greg在評論中建議的那樣:你必須添加#import "UIImageView+AFNetworking.h".

如果您正在使用AFNetworking,為什么不使用UIImageView + AFNetworking類別? 只需導入UIImageView + AFNetworking.h並使用此方法:

- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
              placeholderImage:(UIImage *)placeholderImage
                       success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
                       failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;

編輯:設置圖像后,不要忘記在單元setNeedsLayout上調用setNeedsLayout

在進行異步圖像下載時,無法立即在UITableViewCell上獲取結果圖像。 因此,您應該下載圖像並使用tableView indexPath使用下載圖像陣列顯示它們。

請參考此鏈接使用延遲加載下載圖像並將其顯示在UITableViewCell

謝謝!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM