我一直在尝试在 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)
我感谢您的帮助。谢谢。