swift - Kingfisher 使用自定义 ImageView 下载多个图像

标签 swift uiimageview kingfisher

我想使用 kingfisher 下载多张图片,并使用页面控件(如 instagram 主页 feed)在 Collection View 中显示这些图片。为此,我创建了自定义 ImageView 。我试过如下所示,但显示的图像都是一样的,即使 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)
         }
     }
 }

最佳答案

问题是您正试图在单个 ImageView 中显示多个图像。结果,所有图像都被下载,但只显示最后检索到的图像。您可能想要一些包含照片的 Collection View ,其中:

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

关于swift - Kingfisher 使用自定义 ImageView 下载多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48970847/

相关文章:

ios - 某些自定义 UITableViewCells 未呈现

ios - 在 .xib 上制作 UIImageView 全屏

Swift、Kingfisher 缓存无法正常工作?

ios - 我应该如何快速上传带有图像的文本

ios - 在 IOS/Swift 中创建文本字段集合

swift - 无法在 2 个 View Controller 之间传递 UIImage(没有 Storyboard)

ios - KingFisher + UICollectionView + XCTest 与 NSURLSession 模拟不加载图像

swift - Xcode11 中的 Kingfisher 问题 - 无法找到目标 'Kingfisher' 的模块 'armv7-apple-ios' ;发现 : arm64, arm64-apple-ios

ios - 无法在 Swift 中初始化 Google map

ios - 计算 UITableViewCell 的最佳图像大小