Swift 翠鸟使用自定义图像视图下载多个图像

Swift 翠鸟使用自定义图像视图下载多个图像,swift,uiimageview,kingfisher,Swift,Uiimageview,Kingfisher,我想用翠鸟下载多张图片,并用页面控件(如instagram home feed)在收藏视图中显示这些图片。为此,我创建了自定义图像视图。我试着像下面一样,但显示的图像都是一样的,即使URL不同。我怎样才能解决这个问题?提前谢谢你 import UIKit import Kingfisher class CustomImageView: UIImageView { var lastUrlToLoad: String? func loadMultipleImages(urlSt

我想用翠鸟下载多张图片,并用页面控件(如instagram home feed)在收藏视图中显示这些图片。为此,我创建了自定义图像视图。我试着像下面一样,但显示的图像都是一样的,即使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)
         }
     }
 }

问题是您试图在单个图像视图中显示多个图像。因此,将下载所有图像,但只显示最后检索到的图像。您可能希望有一些包含照片的收藏视图,其中:

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
添加图像预取,这也是翠鸟支持的:

collectionView.prefetchDataSource = self

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

为什么要为给定的图像视图提供多个URL?因为我想在集合视图上显示多个图像,但不像网格。但是每个图像视图只能显示一个图像,所以您应该只为其提供一个URL,而不是列表。如果您演示如何在集合视图中使用此
CustomImageClass
,以及如何调用
loadMultipleImages
方法,您的问题会更好。对此,我深表歉意。我编辑。你能看看吗?非常感谢。