簡體   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