【问题标题】:Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling?从 UITableView 单元格内的 url 异步加载图像 - 滚动时图像更改为错误图像?
【发布时间】:2016-07-06 11:33:20
【问题描述】:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{   static NSString *CellIdentifier = @"cell";

    TVcell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    if (cell == nil)
        cell = [[TVcell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

   cell.txtlabel.text = [[[arrayData objectAtIndex:indexPath.row] valueForKey:@"description"]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];


    cell.IMGLabel.contentMode = UIViewContentModeScaleAspectFill;
    cell.IMGLabel.image = nil;

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",[enclosureUrlArray objectAtIndex:indexPath.row]]];

    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            UIImage *image = [UIImage imageWithData:data];
            if (image) {
                dispatch_async(dispatch_get_main_queue(), ^{
                        cell.IMGLabel.image = image;
                          [cell.IMGLabel setImage:image];
                          [cell.IMGLabel.layer setMasksToBounds:YES];
                          [cell.IMGLabel.layer setCornerRadius:2.5f];
                          [cell setNeedsLayout];

                });
            }
        }
    }];
    [task resume];

【问题讨论】:

  • 使用 SDWebImage 库。它非常易于使用且速度很快。
  • NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval];
  • 这里我得到错误 balachandra

标签: ios uitableview uiimageview


【解决方案1】:

您的问题是您无法保证您的NSUrlRequests 会以与开始时相同的顺序终止。这很糟糕,因为您的单元被重复使用以获得更好的性能,并且可能以奇怪的行为结束。

您可以在此处找到解决方法:Asynchronous downloading of images for UITableView with GCD

或者您可以使用此处列出的工具来帮助您解决此问题:https://stackoverflow.com/a/32601838/3769338

【讨论】:

    猜你喜欢
    • 2013-05-15
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多