【问题标题】:How to edit a UITableViewCell in a completion block from a method called inside the delegate method cellForRowAtIndexPath:如何从委托方法 cellForRowAtIndexPath 中调用的方法编辑完成块中的 UITableViewCell:
【发布时间】:2015-06-18 19:37:56
【问题描述】:

在 UITableView 委托方法 cellForRowAtIndexPath:(NSIndexPath *)indexPath 中,我想为一个单元格 imageView 设置图像。如果图像不可用,我想下载它,然后在完整块中异步设置它。问题是因为单元格是可重用的,可能在调用完成块时,单元格可能不再存在。 调用完成块时如何更新单元格?或者这样可以吗?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FriendTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"Friend Cell"];

    Friend *friend = self.friends[indexPath.row];

    if (friend.picture) {
        cell.userProfileImageView.image = [UIImage imageWithData:pictureData];
    } else {
        cell.userProfileImageView.image = nil;

        NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=normal&return_ssl_res", friend.facebookId]];

        NSURLRequest *urlRequest = [NSURLRequest requestWithURL:pictureURL];

        // Run network request asynchronously
        [NSURLConnection sendAsynchronousRequest:urlRequest
                                           queue:[NSOperationQueue mainQueue]
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
             if (connectionError == nil && data != nil) {
                 friend.picture = data;
                 FriendTableViewCell *cellToUpdate = (FriendTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
                 cellToUpdate.userProfileImageView.image = [UIImage imageWithData:data];
             }
         }];
    }

    return cell;
}

【问题讨论】:

    标签: ios objective-c uitableview


    【解决方案1】:

    在您的完成处理程序中,只需要求表重新加载受影响的行。由于您的数据模型现在有图片,它将正确更新。这也可以防止单元格离开屏幕,这将导致 noop()。当您向后滚动时,一切都会好起来的,因为图片现在在您的数据模型中。

    比如:

    [NSURLConnection sendAsynchronousRequest:urlRequest
                                               queue:[NSOperationQueue mainQueue]
                                   completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                 if (connectionError == nil && data != nil) {
                     friend.picture = data;
                     self.tableView reloadRowsAtIndexPaths:@[indexPath]
                                          withRowAnimation:UITableViewRowAnimationNone]
                 }
             }];
    

    如果您决定在非主线程中运行异步请求,则需要在主线程上安排行重新加载。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-22
      • 1970-01-01
      • 2020-10-29
      • 2014-11-06
      相关资源
      最近更新 更多