如何通过单击更改集合视图单元格中的标签颜色

mac*_*ack 5 ios uicollectionview swift

我有一些单元格的集合视图。在我的单元格中,我有一个标签来显示国家名称列表。每次单击每个单元格标签时,我都会在集合视图下方的表视图中显示一些数据。

当我按下任何单元格标签时,我需要将该标签的文本更改为红色。其他标签名称应为黑色。

怎么做?我尝试了下面的代码,但是当我在该单元格中选择任何标签名称时,所有单元格标签都变为红色。

我该如何解决?

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {


        if let cell = collectionView1.cellForItemAtIndexPath(indexPath) {

            var label = cell.viewWithTag(100) as? UILabel


            label!.textColor = UIColor.redColor()

        }
    }
Run Code Online (Sandbox Code Playgroud)

Igo*_*yuk 2

您的标签不会更新,因为您需要刷新单元格。所以我可以为您提供的最佳解决方案 -在自定义单元格类setSelected中的方法中更改标签颜色

编辑:


override var setSelected(selected: bool) {
    if (selected) { 
       self.youLabel!.textColor = UIColor.redColor()
    } else {
       self.youLabel!.textColor = UIColor.blackColor()
}
Run Code Online (Sandbox Code Playgroud)

这是您的自定义类中的函数示例。抱歉,如果有错误 - iPhone 回复