我的应用程序中有一个带有本地镜像的工作 UIScroll View 。然而,我希望我的图像能够从 URL 下载并存储在缓存中。我见过几个执行此操作的示例库,例如 sdwebimage、kingfisher 等,但这些示例使用 UITableview 和单元格。我正在使用 UIImage 数组作为 ScrollView 。我真正想要的是下载并缓存图像并将它们存储在数组 IconsArray = [icon1, icon2, icon3] 中,其中 icon1 到 icon3 是从 URL 下载的图像。我该怎么做?有什么好的教程或者有好心人可以向新手展示一些代码吗?
提前致谢
最佳答案
如果您下载许多图像,您将遇到内存问题,并且当您的数组超出范围时,您的工作也会被丢弃,但是如果您想实现建议的解决方案,您可能想要做的是使用字典而不是数组。它只会让您更轻松地找到所需的图像。所以你可以像这样实现字典:
var images = [String : UIImage]()
对于 key ,您可以只使用 URL 字符串(足够简单的解决方案),因此安全访问图像将如下所示:
let urlString = object.imageUrl.absoluteString //or wherever you're getting your url from
if let img = self.images[urlString] {
//Do whatever you want with the image - no need to download as you've already downloaded it.
cell.image = img
} else {
//You need to download the image, because it doesn't exist in your dict
...[DOWNLOAD CODE HERE]...
//Add the image to your dictionary here
self.images[object.imageUrl.absoluteString] = downloadedImage
//And do whatever else you need with it
cell.image = downloadedImage
}
正如我所说,这有一些缺点,但它可以快速实现您所要求的内容。
关于ios - 如何将 URL 中的图像加载到 UIImage 数组中并使用 Swift 在 UIScrollView 中使用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42542784/