ios - Swift:如何提高文档中图像的加载速度?

标签 ios swift

我的应用程序将照片保存到本地文档文件夹,我使用 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/

相关文章:

android - flutter ios无法运行,获取widgets库异常并丢失设备连接

ios - UILongPressGestureRecognizer 不工作,但将它换成 UITapGestureRecognizer 工作正常。为什么?

swift 协议(protocol)扩展默认实现与类中的实际实现

ios - 我可以使用 Xcode 在模拟器设备上浏览 Core Data 持久存储吗?

ios - 如何修复 Swift 中的 "ActionSheet of UIAlertController has the conflict constraint"错误

ios - 我正在尝试在 Windows PC 中使用 IOS Simulator/Emulator 或 iOS SDK a.Is it possible to install IOS Simulator/Emulator or iOS SDK in windows PC

swift - 对任意值的字典数组进行排序

ios - UISearchBar searchBarCancelButtonClicked 未使用 Swift 3 调用

objective-c - 使用 Swift 4 在 Xcode 9 上找不到“ProjectName-Swift.h”文件?

ios - swift/OpenGL ES 2.0 - 从 YUV420 缓冲区创建纹理