如何替换单元格 CollectionView 中的图像

How to replace an image in a cell CollectionView

我以编程方式创建了集合。一切都很完美。但是现在我需要替换某个单元格中的图片。如何识别cell并获取UIImage?

var imagesOfPaletes = [UIImage]()

override func viewDidLoad() {
    super.viewDidLoad()
    
    if imagesOfPaletes == [] {
        for i in 0...11 {
            let palete = UIImage(named: "\(i)-0")!
            imagesOfPaletes.append(palete)
        }
    }
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
    let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath as IndexPath)
    
    let img2 = imagesOfPaletes[indexPath.item]
    imageView2.image = img2
    myCell.contentView.addSubview(imageView2)
    
    return myCell
}

如果要访问某个单元格,请使用“collection.cellForItem(at: inedexPath)”,然后使用返回的单元格对象访问图像。

因此,要访问图像,您可以使用“collectionCell.subViews”遍历单元格子视图并检查子视图的类型。检查以下示例:-

let collectionCell = UICollectionViewCell()
collectionCell.addSubview(UIImageView())
for subView in collectionCell.subviews {
    if subView is UIImageView {
            debugPrint("Ok")
        }
    debugPrint("subview is \(subView)")
}