小编tat*_*dev的帖子

DispatchQueue.main.async 阻塞主线程

我一直在尝试在 Swift 3.0 中创建一个照片库,我想将存储在文档目录中的图像异步加载到集合视图中。我尝试过DispatchQueue.main.async,但它会阻塞主线程并使应用程序冻结几秒钟:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let identifier = "ImageCell"
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! ImageCell
    let url = self.imageURL[indexPath.row]
    cell.lazyLoadImage(from: url)
    return cell
}
Run Code Online (Sandbox Code Playgroud)

和 ImageCell 类:

class ImageCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!

    func lazyLoadImage(from url: URL) {
        DispatchQueue.main.async {
            if let image = UIImage(contentsOfFile: url.path) {
                self.imageView.image = image
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我感谢您的帮助。谢谢。

ios uicollectionview swift

2
推荐指数
1
解决办法
3536
查看次数

标签 统计

ios ×1

swift ×1

uicollectionview ×1