简体   繁体   中英

How to replace an image in a cell CollectionView

I created the collection programmatically. Everything works perfectly. But now I need to replace a picture in a certain cell. How to identify the cell and get to the 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
}

if you want to access a certain cell use "collection.cellForItem(at: inedexPath)" and then use the returned cell object to access the image.

So to access the image you can loop through cells subviews using "collectionCell.subViews" and check the type of the subView. check the following example:-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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