tat*_*dev 2 ios uicollectionview swift
我一直在尝试在 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)
我感谢您的帮助。谢谢。
首先切换到后台线程并在其上加载图像,然后再次切换到主线程并显示图像。
func lazyLoadImage(from url: URL) {
DispatchQueue.global(qos: .userInteractive).async {
if let image = UIImage(contentsOfFile: url.path) {
DispatchQueue.main.async {
self.imageView.image = image
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3536 次 |
| 最近记录: |