繁体   English   中英

如何在集合视图的可重用单元格内引用/更新 label?

[英]How to reference/update label inside a reusable cell of a collection view?

我有一个带有可重用单元格的集合视图。 该单元格有一个背景,label 和按钮。 我可以参考每个单元格中的背景。 我想根据单元格的背景在按下按钮时更新 label 中的文本。 我无法引用单元格。 let cell = collectionView.cellForItem(at: indexPath) 给我一个错误。 如何引用此单元格?

如果 label 在用户滚动集合视图时被重置,我没问题。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyColectionCell
    cell.CellBG.image = UIImage(named: ButtonBGs[indexPath.row])
    cell.CellBG.layer.cornerRadius=10

    cell.layer.shadowColor = UIColor.black.cgColor
    cell.layer.shadowOffset = CGSize(width: 1, height: 10)
    cell.layer.shadowOpacity = 0.3
    cell.layer.shadowRadius = 10
    cell.layer.masksToBounds = false

    cell.Info.tag = indexPath.row
    cell.Info.addTarget(self, action: #selector(Info), for: .touchUpInside)

    cell.CellText.text = " "
    cell.CellText.tag = indexPath.row
    return cell
}

@objc func Info(sender: UIButton){
    let indexPath = IndexPath(row: sender.tag, section: 0)
    let cell = collectionView.cellForItem(at: indexPath) //gives me error "Reference to member 'cellForItem' cannot be resolved without a contextual type"

    if((ButtonBGs[indexPath.row])=="bt-tower"){
        cell.CellText.text = "New Text"
    }
}

我会推荐一种不同的方法。 您提供的代码表明所有这些都可以在单元格本身中执行。

给它一个包含图像名称的String类型的属性,在func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath:内分配它,并在 Button @IBAction内执行按钮操作/比较。

此外,操作图层的代码也应该在单元格本身中。 cellForItemAt indexpath: function 应该只提供单元格呈现的数据。

我在一些帮助下想通了。 我正在为 label 文本使用数组并将标签 alpha 保持为 0。当我需要显示它时,我更改 alpha 并重新加载数据 self.myCollection.reloadItems(at: [indexPath]) 这样只有文本显示索引单元格。

暂无
暂无

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

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