ios - UITableViewCell 图像从 url 加载

标签 ios iphone uitableview

我在从 url 加载图像以显示在表格中时遇到问题。我目前有以下代码来处理扩展 UITableViewCell 的类中的图像加载:

- (void) initWithData:(NSDictionary *) data{

     NSDictionary *images = [data objectForKey:@"images"];
    __block NSString *poster = [images objectForKey:@"poster"];

        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{

            NSURL *posterURL = [[NSURL alloc] initWithString:poster];
            NSData *imageData = [NSData dataWithContentsOfURL:posterURL];

            if (imageData != nil) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    // 4. Set image in cell
                    self.backgroundImage.image = [UIImage imageWithData:imageData];
                    [self setNeedsLayout];
                });
            }
        });


    self.backgroundImage.image = [UIImage imageNamed:@"static"];
}

initWithData 方法是从 tableView:cellForRowAtIndexPath: delegate 中的 ViewController 调用的。 在我滚动之前,一切都按预期工作。根据我的阅读,TableView 单元格被回收,并且由于图像正在异步加载,我得到包含错误图像的行。此外,图像不会被缓存并在单元格显示时再次加载

例如:滚动到中间并立即向上滚动。第一个单元格将包含与未完成加载的中间单元格对应的图像。

有什么帮助或建议吗?非常感谢:)

最佳答案

首先,如评论所述,我肯定会推荐使用现有的框架/组件来完成这项工作。

最好的候选人可能是:

https://github.com/rs/SDWebImage

https://github.com/enormego/EGOImageLoading

或者如果你还想要一个通用的网络库

https://github.com/AFNetworking/AFNetworking

也就是说,如果您仍想自己尝试,您可能希望使用 NSMutableDictionary 实现缓存,使用 indexPath 作为键,将图像作为值。

假设你有一个初始化的实例变量NSMutableDictionary *imageCache

在您的 cellForRowAtIndexPath 方法中,在尝试进行任何图像加载之前,您将通过执行类似的操作来检查您的缓存是否已经具有该索引的图像

if(! imageCache[indexPath])
{
  // do your web loading here, then once complete you do
  imageCache[indexPath] = // the new loaded image
}
else
{
  self.backgroundImage.image = imageCache[indexPath];
}

关于ios - UITableViewCell 图像从 url 加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20250104/

相关文章:

ios - fatal error : index out of range tableview with two sections

ios - 构建聊天应用程序时应该使用 UITableView 还是 UICollectionView?

ios - Swift Tableview 获取特定单元格不工作

ios - 将多个数据数组显示到单个 TableView 部分的有效方法

ios - CCLabelTTF 支持的字体?

iPhone 使用 SSL 登录网站

iphone - iOS:来自 Photoshop 的 CIFilter (Hue) 的值

ios - 删除 didSelect 函数中的 UITabBar 项目

ios - 在容器 View 中,导航 Controller 的导航栏未调整大小以包含状态栏

iOS 如何在应用程序中实现一个长的、可滚动的日志功能?