繁体   English   中英

在swift 4.0中点击收集视图单元格时更改标签的文本

[英]Changing the text of a label when a collection view cell is tapped in swift 4.0

轻按收集视图单元格时,更改标签的文本时出现问题。 我试过使用didSelectItemAtdidHighlightItemAt但没有任何效果。 这是我的单元格的样子:

细胞

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
    cell.subjectName.text = "Selected"
}

你需要

let cell = collectionview.cellForItem(at: indexPath) as! CollectionViewCell
cell.subjectName.text = "Selected"

但请注意,由于单元格出队,如果仍然滚动显示该单元格,则此更改是暂时的,如果您在周围滚动,则可能会在该索引内找到另一个文本,因此请在集合的数组模型中反映更改并重新加载该indexPath

var statesArr = ["Selected","Default",,,,,,,,,,]

didSelectItemAt内部

statesArr[indexPath.row] = "Selected"
self.collectionView.reloadItems(at:[indexPath])

cellForItemAt内部

let cell = ///
cell.subjectName.text = statesArr[indexPath.row]

暂无
暂无

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

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