繁体   English   中英

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

[英]How to replace an image in a cell CollectionView

我以编程方式创建了集合。 一切都很完美。 但是现在我需要替换某个单元格中的图片。 如何识别小区并到达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)”,然后使用返回的单元格 object 访问图像。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM