Kingfisher使用自定义图像视图下载多个图像

时间:2018-02-25 06:25:30

标签: swift uiimageview kingfisher

我想用翠鸟下载多个图像,并在页面控制(如instagram家庭饲料)的集合视图中显示这些图像。为此,我创建了自定义图像视图。我尝试过如下,但即使网址不同,显示的图像也是一样的。我怎样才能解决这个问题?提前谢谢!

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)
         }
     }
 }

1 个答案:

答案 0 :(得分: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()
}