【问题标题】:How can I load Images from URL into an UIImage Array and use them in UIScrollView with Swift如何将 URL 中的图像加载到 UIImage 数组中并在 UIScrollView 中使用 Swift
【发布时间】:2017-03-01 21:51:28
【问题描述】:

我的应用中有一个带有本地图像的 UIScroll 视图。但是,我希望我的图像将从 URL 下载并存储在缓存中。我见过几个示例库,例如 sdwebimage、kingfisher 等,但这些示例使用 UITableview 和单元格。我正在为我的滚动视图使用 UIImage 数组。我真正想要的是我下载并缓存我的图像并将它们存储在 Array IconsArray = [icon1, icon2, icon3] 中,其中 icon1 到 icon3 是从 URL 下载的图像。我该怎么做?那里有任何不错的教程,或者有好心的人向菜鸟展示一些代码吗?

提前致谢

【问题讨论】:

    标签: ios arrays swift uiscrollview uiimage


    【解决方案1】:

    如果您要下载许多图像,您将遇到内存问题,并且当您的阵列超出范围时,您的工作也会被丢弃,但是如果您想实施您提出的解决方案,您可能想要做的是使用字典而不是数组。它只会让您更容易找到您正在寻找的图像。所以你可以像这样实现字典:

    var images = [String : UIImage]()
    

    对于密钥,您可以只使用 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
    }
    

    正如我所说,这有一些缺点,但它可以快速实现您的要求。

    【讨论】:

    • 谢谢,我会试试的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    相关资源
    最近更新 更多