我的应用程序将照片保存到本地文档文件夹,我使用 UICollectionView 显示该文件夹中的所有图像。但每当我尝试打开 CollectionView 时,通常需要几秒钟才能打开。我想可能是图片文件太大了,每张照片大约10MB。我也尝试使用缩略图在 CollectionView 中显示,但仍然太慢。知道如何加快速度吗?
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! SPCell
// Configure the cell
cell.imageView.image = loadImage(fileName: self.fileURLs[indexPath.row])
return cell
}
func loadImagesFromDocuments(){
let fileManager = FileManager.default
let documentsURL = NSHomeDirectory() + "/Documents/Secure/"
do {
fileURLs = try fileManager.contentsOfDirectory(at: URL(string: documentsURL)!, includingPropertiesForKeys: nil)
} catch {
print("Error while enumerating files : \(error.localizedDescription)")
}
}
func loadImage(fileName: URL) -> UIImage? {
do {
let imageData = try Data(contentsOf: fileName)
return UIImage(data: imageData)
} catch {
print("Error loading image : \(error)")
}
return nil
}
最佳答案
当前的问题是每次单元格出现时都加载图像,而不是
var fileURLs = [URL]()
成功
var fileImages = [UIImage]()
然后在viewDidLoad
内
fileImages = fileURLs.compactMap { self.loadImage(fileName: $0) }
关于ios - Swift:如何提高文档中图像的加载速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59687518/