ios - 如何异步加载 CollectionView 单元格图像?

标签 ios swift asynchronous uiimage uicollectionview

现在我有一个 UICollectionView(水平滚动),其中的单元格包含 UIImage。我使用它来显示 UIImage 过滤器,就像 Instagram 那样。但是当我滚动查看图像在实现过滤器后的样子时 - 它卡住了。我怎样才能让它像在 Instagram 中那样流畅?

我的代码:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell: imageFilterCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! imageFilterCell

    NSOperationQueue.mainQueue().addOperationWithBlock {             
        cell.imageView.image = self.applyFilterTo(self.image!, filter: self.filtersImages[indexPath.row])
        cell.imageView.layer.cornerRadius = 5
        cell.imageView.layer.masksToBounds = true
        cell.filterLabel.text = self.filtersLabels[indexPath.row]
    }

    return cell
}

其中 applyFilter() 为我的图像实现了一个过滤器。

有什么解决方案可以使滚动流畅并防止卡顿?

最佳答案

试试这个

let queue = NSOperationQueue()

        let op1 = NSBlockOperation { () -> Void in

            let img1 = self.applyFilterTo(self.image!, filter: self.filtersImages[indexPath.row])

            NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                cell.imageView.image = img1
            })
        }


queue.addOperation(op1);
cell.imageView.layer.cornerRadius = 5
        cell.imageView.layer.masksToBounds = true
        cell.filterLabel.text = self.filtersLabels[indexPath.row]

关于ios - 如何异步加载 CollectionView 单元格图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35772125/

相关文章:

c# - .Result 或在 Task.WhenAll 之后等待

asynchronous - 如果某些情况发生,则完成 future

ios - 无法将形状层添加到 View 的层中

swift - 带有 json 编码的 Alamofire post 请求

objective-c - 关于代表的一些困惑

ios - 检查 collectionView 中的文本字段是否为空

swift - 选择选项卡并更改加载 View 上的段

c# - 析构函数中的异步操作

ios - 如何使用 IOS DJI-SDK 以编程方式从无人机下载图像

php - 使用 Alamofire Swift 5 上传文件有问题吗?