【问题标题】:How to replace an image in a cell CollectionView如何替换单元格 CollectionView 中的图像
【发布时间】:2021-11-29 05:22:43
【问题描述】:

我以编程方式创建了集合。一切都很完美。但是现在我需要替换某个单元格中的图片。如何识别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
}

【问题讨论】:

  • 一般来说,如果你需要重新加载一个单元格,你会调用其中一个collectionView重新加载方法。
  • 我无法从你所包含的代码中看出——只有你可以从你的程序使用的任何逻辑中确定。
  • 您将哪个图像放入具有特定 indexPath 的单元格中,以便您能够计算更新图像并重新加载它的单元格的 indexPath
  • 如何将它重新加载到这个特定的单元格中?有什么方法可以通过索引路径将图像设置到 UIImage 中
  • tableView.reloadRows(at:[indexParh of cell with new image)

标签: ios swift uicollectionview uikit


【解决方案1】:

如果要访问某个单元格,请使用“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)")
}

【讨论】:

  • 谢谢,我到了牢房。但是我无法访问 ImageView,它是以编程方式放置在上面的!怎么办????????
  • 嗨 Sash,检查答案编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-11
  • 2019-04-22
相关资源
最近更新 更多