【问题标题】:How to async load images on dynamic UITableView?如何在动态 UITableView 上异步加载图像?
【发布时间】:2015-05-22 05:52:38
【问题描述】:

现在我有一个带有图像和标签的自定义单元格。后来我通过以下方式打印这些单元格:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell:customCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! customCell

    var url = NSURL(string: postCover[indexPath.row])

    if let data = NSData(contentsOfURL: url!) { 
        cell.cellImage.image = UIImage(data: data)
    }

    var title = postTitle[indexPath.row]

    cell.cellLabel.text = title

    let indexPath = tableView.indexPathForSelectedRow()

    return cell
}

当我打开一个应用程序并滚动它时,它会冻结。如何修复此错误?

我读到过,我必须在我的 tableView 中使用异步图像加载,但我不是已经异步加载它们了吗?

我搜索并考虑了 4-5 天,但一无所获。谁能给我一些建议,好吗?

【问题讨论】:

标签: ios uitableview swift asynchronous


【解决方案1】:

您可以使用 GCD as- 为每个单元异步安排图像下载-

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell:customCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! customCell

    var url = NSURL(string: postCover[indexPath.row])

cell.imageView.image = nil;
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
        dispatch_async(queue, ^(void) {

            NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:parsedData[@"imageLR"]];

            UIImage* image = [[UIImage alloc] initWithData:imageData];
            if (image) {
                 dispatch_async(dispatch_get_main_queue(), ^{
                     if (cell.tag == indexPath.row) {
                         cell.imageView.image = image;
                         [cell setNeedsLayout];
                     }
                 });
             }
        });

return cell
}

对于 Swift,你可以这样做

if let data = self.cache.objectForKey(urlString) as? NSData {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
            let image = UIImage(data: data)
            dispatch_async(dispatch_get_main_queue()) {
                cell.imageView.image = image;
            }
        }

【讨论】:

  • 很好,但你能把它翻译成 Swift 吗?
  • @OrkhanAlizade,我一定会这样做
  • 这不会缓存图像,并且随着用户滚动数据将再次下载...使用 SDWebImage ,它将同时进行下载和缓存
  • 该方法的问题是没有缓存,因此每次滚动表格时都会加载单元格图像。使用缓存策略或 SDWebimageCache 库来解决这个问题。
  • 对于具有少量单元格的表格视图,您可以使用上述方法,也可以仅在您可以将下载的图像保存在字典中以 url 作为键时下载图像,并且如果您需要缓存而不是所有人建议的缓存,使用 SDWebImage
【解决方案2】:

您可以在 gitHub 上使用第三方库 SDWebImage。它基于 Objective-C,还有一个基于 Swift 的库Kingfisher。也许这就是你想要的。

【讨论】:

  • KingFisher 非常简单直接。但我有一个问题,在翠鸟完成下载后刷新手机最干净的方法是什么?是否必须设置回调并调用 .reloadRowsAtIndexPath?
【解决方案3】:

在 swift.Import AFNetworking 头文件中创建一个桥接头

然后找到这些方法setImageWithURLRequest

cell.imageView.setImageWithURLRequest你可以这样调用

【讨论】:

  • 你能帮我聊聊吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多