ios - 使用 AFNetworking 同时加载 UITableViewCell 图像和文本标签时遇到问题

标签 ios objective-c uitableview

我遇到的问题与 SE 上的其他问题类似,因为我的 UITableView Controller 会立即加载文本标签,但只会在我 ScrollView 并将项目移出屏幕时加载我的缩略图。

我尝试将 [self.tableView reloadData] 添加到 AFHTTPRequestOperation setCompletionBlockWithSuccess,但有一个缺点。它显然运行得太频繁了。

出现问题的方法如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString *fullPath;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCell" forIndexPath:indexPath];

    Child *child = _children[indexPath.row];

    if([child.data.thumbnail length] == 0) {
        fullPath = @"reddit.png";
    } else {

        // Get the thumbnail
        NSURL *url = [NSURL URLWithString:child.data.thumbnail];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];

        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

        fullPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[url lastPathComponent]];

        [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:fullPath append:NO]];

        [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
            NSLog(@"bytesRead: %lu, totalBytesRead: %lld, totalBytesExpectedToRead: %lld", (unsigned long)bytesRead, totalBytesRead, totalBytesExpectedToRead);
        }];

        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//            [self.tableView reloadData];

            NSLog(@"RES: %@", [[[operation response] allHeaderFields] description]);

            NSError *error;

            if(error) {
                NSLog(@"ERR: %@", [error description]);
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"ERR1: %@", [error description]);
        }];

        [operation start];
    }

    cell.textLabel.text = child.data.title;
    cell.imageView.image = [UIImage imageNamed:fullPath ];
    return cell;
}

最佳答案

不必在每次加载图像时都重新加载整个 TableView ,您可以直接在完成 block 内的单元格上设置该图像。

但是,如果您这样做,您需要检查该单元格是否仍然可见,并且它是否仍在您开始加载 View 时所在的同一索引路径上,否则您可能会将图像设置在一个单元格上已被重用,现在在 TableView 中处于不同的位置。

关于ios - 使用 AFNetworking 同时加载 UITableViewCell 图像和文本标签时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29218776/

相关文章:

iphone - 开始和停止按钮,需要禁用和隐藏然后重新启用和可见

ios - tableview 中的 Cell Click 不会快速导航到新 Controller

iphone - UIKit中的类如何实现深拷贝?

ios - 以编程方式设置自定义图像大小和位置

ios - UITableViewCell subview 显示在单元格外部

ios - 搜索栏处于事件状态时,快速 TableView 被锁定

iphone - 如何为 Apple 的 Large Image Downsizing iOS 示例设置最大缩放限制?

ios - 获取请求模板-获取所有对象

ios - 移动 iOS 后单击时按钮消失

ios - 来自 tableView 标题部分的快速奇怪的 tableview 滚动行为