单元格填充后如何在单元格中加载/显示UIImageView

时间:2019-04-08 21:58:53

标签: ios swift uicollectionview

我有UICollectionView张图片,在每个单元格的一角有一个水印(或一个小图标)。图像是远程获取的,图标是硬编码的(本地)。除一个难看的问题外,其他所有东西都工作正常:本地水印图标在获取图像时先加载每个单元格,但外观不好。 --->我正在寻找一种在每个单元格填充后(或更糟的情况是,在所有单元格填充后)加载/显示水印图标(UIImageView)的方法。感谢您的帮助!

1。。这可能吗? 2。。我将在哪里实现它:cellForItemAtviewDidLoad等? 3。,然后输入代码。请注意,我是编码的新手。

这是我如何使用远程存储图像(不包括监听器)填充collectionView的方法:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myproductCell", for: indexPath) as! MyProductsCollectionCell
        if (self.products.indices.contains(indexPath.row)) {
            let product = self.products[indexPath.row]
            cell.configureWithProduct(Product(caption: product.caption, videoUrl: product.videoUrl, imageUrl: product.imageUrl))

        }
        return cell
    }

我刚刚为本地存储的水印(图标)创建了一个出口:

@IBOutlet weak var watermark: UIImageView!

2 个答案:

答案 0 :(得分:0)

使用SDWebImage库。

首先使用cocoapods安装库

pod 'SDWebImage'

将SDWebImage库导入MyProductsCollectionCell上方,并使用SDWebImage提供的方法设置图像。

该库将处理异步下载,图像设置并将其缓存。

import SDWebImage

class MyProductsCollectionCell: UICollectionViewCell {

    @IBOutlet weak var watermark: UIImageView!
    // rest of your properties.

    func configureWithProduct(_ product: Product) {
        cell.watermark.sd_setImage(with: URL(string: product.imageUrl), placeholderImage: UIImage(named: "placeholder.png"))
        // set values to the rest properties.
    }
}

答案 1 :(得分:-1)

我没有看到您的代码,因此无法发表评论。但肯定不在viewDidLoad中。

您可以使用块在cellForItemAt中实现此功能。

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // download the image on the background thread
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // once you have the image downloaded, 
        // set the image on a main thread
        // in the completion handler
        dispatch_async(dispatch_get_main_queue, ^{
            callback(yourImage); // this can be a call to your method.
        });
    });
}
相关问题