【发布时间】:2018-11-03 04:32:56
【问题描述】:
我一直在尝试在 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
}
还有 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
}
}
}
}
感谢您的帮助。谢谢。
【问题讨论】:
-
如果您在应用程序冻结时暂停应用程序,主线程的回溯中是什么?
-
其实你什么都没做我的意思是你在主线程中,并且在主线程中调度块
-
如果图像只是文件,我不会认为您需要异步发送任何东西;只需加载图像。如果您的图像文件非常大,请考虑在单元格中加载更快的缩略图。
标签: ios swift uicollectionview