使用翠鸟直接将UIImage设置为UIImageView

问题描述 投票:1回答:1

我想直接使用UIImage设置图像,而不是任何Source,Resource。我已经拥有了我的图像,并希望通过缓存将其设置为我的imageView。

let myImage = UIImage

kingfisherView.kf.setImage(with: myImage)

我希望这样做,就像我将图像设置为UIImageView即

UIImageView.image = myImage

但是有了缓存

我不是从我自己生成它们的源(Latex)下载图像。用缓存来缓存它们

let cache = ImageCache.default

cache.store(renderedLaTeX ?? UIImage(), forKey: "image\(indexPath.row)")

我只想将缓存的图像设置为我的imageView。

UIImage.image = cachedImage

当我在CollectionViewCell上下滚动时,它不能正常工作并且一次又一次地加载图像

或任何其他方式这样做,以便我没有反复加载imageView与图像。我的ImageViewUICollectionViewCell

ios swift uiimageview nscache kingfisher
1个回答
2
投票

您可以通过以下方式将现有图像存储在Kingfisher缓存中:

let image: UIImage = //...
ImageCache.default.store(image, forKey: cacheKey)

默认情况下,翠鸟使用url.absoluteString作为cacheKey

因此,如果您已经从某个地方下载了图像并且仍然有这个URL,您可以自己将它们存储在缓存中,下次Kingfisher将不会下载图像,但使用缓存的图像

如果您只想在不下载的情况下进行缓存,则可以通过以下方式检索图像:

cache.retrieveImage(forKey: "cacheKey") { result in
    switch result {
    case .success(let value):
        print(value.cacheType)

        // If the `cacheType is `.none`, `image` will be `nil`.
        print(value.image)

    case .failure(let error):
        print(error)
    }
}

但是,由于您在集合视图中使用它,请确保在重新使用collectionViewCell时停止加载

单元格中的示例: 我们将imageKey存储在单元格中,当Cache返回图像给我们时,我们确保单元格尚未被重用但仍需要此图像。如果重复使用单元格,那么在prepareToReuse()中我们删除存储的imageKey

class LatexCell: UICollectionViewCell {
    @IBOutlet var formulaImageView: UIImageView!
    private var imageKey: String?

    func setup(with imageKey: String) {
        self.imageKey = imageKey
        ImageCache.default.retrieveImage(forKey: imageKey) { [weak self] result in
            guard self?.imageKey == imageKey else { return } // cell have been reused
            switch result {
            case .success(let value):
                self?.formulaImageView.image = value.image

            case .failure(let error):
                break /// no image stored, you should create new one
            }
        }
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        imageKey = nil
        formulaImageView.image = nil // Probably want here placeholder image
    }
}   
© www.soinside.com 2019 - 2024. All rights reserved.