【问题标题】:Kingfisher download multiple images with custom image viewKingfisher 使用自定义图像视图下载多个图像
【发布时间】:2018-02-25 06:25:30
【问题描述】:

我想用 kingfisher 下载多张图片,并通过页面控制(如 instagram 主页)在收藏视图中显示这些图片。为此,我创建了自定义图像视图。我尝试如下,但显示的图像都是相同的,即使 url 不同。我怎样才能解决这个问题?提前谢谢!

import UIKit
import Kingfisher

class CustomImageView: UIImageView {

    var lastUrlToLoad: String?

    func loadMultipleImages(urlStrings: [String]) {

        for urlString in urlStrings {

            lastUrlToLoad = urlString
            guard let url = URL(string: urlString) else { return }
            let resouce = ImageResource(downloadURL: url, cacheKey: urlString)

            KingfisherManager.shared.retrieveImage(with: resouce, options: nil, progressBlock: nil) { [weak self] (img, err, type, url) in
                if err != nil {
                    return
                }

                if url?.absoluteString != self?.lastUrlToLoad {
                    return
                }

                DispatchQueue.main.async {
                    self?.image = img
                }
            }
        }
    }
}

编辑

我就是这样用这个方法的。

class CollectionView: UICollectionViewCell {

    @IBOutlet var imageView: CustomImageView!

     var post: Post? {
         didSet {
             guard let urlStrings = post?.imageUrls else { return }
             imageView.loadMultipleImages(urlStrings: urlStrings)
         }
     }
 }

【问题讨论】:

  • 为什么要为给定的图像视图提供多个 URL?
  • 因为我想在集合视图上显示多个图像,但不像网格。
  • 但是每个图像视图只能显示一张图像,所以你应该只给它一个 URL,而不是一个列表。如果您在集合视图中展示如何使用此CustomImageClass 以及如何调用loadMultipleImages 方法,您的问题会好得多。
  • 很抱歉。我编辑了。你会看看吗?谢谢!

标签: swift uiimageview kingfisher


【解决方案1】:

问题是您试图在单个图像视图中显示多个图像。结果,所有图像都已下载,但仅显示最后检索到的图像。您可能希望有一些带有照片的集合视图,其中:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return imageUrls.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    //dequeueReusableCell with imageView

    cell.imageView.kf.setImage(with: imageUrls[indexPath.row])

    return cell
}

您可以选择遵循UICollectionViewDataSourcePrefetching 来添加图像预取,Kingfisher 也支持:

collectionView.prefetchDataSource = self

func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
    ImagePrefetcher(urls: indexPaths.map { imageUrls[$0.row] }).start()
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    相关资源
    最近更新 更多