滚动时更新 UITableViewCell



我正在尝试将图像从服务器异步加载到单元格。但是图像在滚动时不会改变,只有在滚动停止后才会改变。"加载"消息仅在滚动停止后才会显示在控制台中。我希望滚动时图像出现在单元格中。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CustomCell *cell = (CustomCell *)[_tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
    ZTVRequest *request = [[ZTVRequest alloc] init];
    [request getSmallImg completionHandler:^(UIImage *img, NSError *error) {
        if (! error) {
            NSLog(@"loaded")
            cell.coverImgView.image = img;
        }
    }];
    return cell;
}

我正在使用NSURLConnection加载图像。我在这个答案中找到了解决方案:丹尼尔·迪基森的 https://stackoverflow.com/a/1995318/1561346

在这里:

在您停止滚动之前不会触发连接委托消息的原因是,在滚动期间,运行循环处于UITrackingRunLoopMode 中。 默认情况下,NSURLConnection仅以NSDefaultRunLoopMode方式安排自身,因此您在滚动时不会收到任何消息。

以下是在"通用"模式下安排连接的方法,其中包括UITrackingRunLoopMode

NSURLRequest *request = ...
NSURLConnection *connection = [[NSURLConnection alloc]
                               initWithRequest:request
                               delegate:self
                               startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop]
            forMode:NSRunLoopCommonModes];
[connection start];

请注意,您必须在初始值设定项中指定startImmediately:NO,这似乎与Apple的文档背道而驰,该文档建议即使在启动后也可以更改运行循环模式。

最新更新