我有一UICollectionView
图像,在每个单元格的角落里我有一个水印(或一个小图标(。图像是远程获取的,图标是硬编码的(本地(。除了一个丑陋的问题外,一切都很好:本地水印图标首先加载每个单元格,同时获取图像,这看起来并不好。---> 我正在寻找一种在填充每个单元格后加载/显示水印图标 ( UIImageView
( 的方法(或更糟糕的情况,在所有单元格填充后(。您的帮助将不胜感激!
1. 这可能吗?2. 我将在哪里实现它:cellForItemAt
、viewDidLoad
等?3.然后代码是什么。请注意,我对编码相对较新。
这就是我使用远程存储图像填充集合视图的方式(不包括侦听器(:
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!
使用 SDWebImage 库。
首先使用 cocoapods 安装库
pod 'SDWebImage'
导入MyProductsCollectionCell
上方的 SDWebImage 库,并使用 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.
}
}
我没有看到你的代码,所以我无法评论。但绝对不在视野中DidLoad。
您可以使用块在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.
});
});
}