[英]how to change the label colour in collection view cell by click
I have one collection view with some cells. 我有一个带有一些单元格的集合视图。 Inside my cells I have one label to show a list of country names.
在我的单元格内,我有一个标签显示国家/地区名称列表。 And on every click of each cell labels I will display some data in table view below my collection view.
每次单击每个单元格标签,我都会在我的集合视图下方的表格视图中显示一些数据。
When I press any cell label I need to turn that label's text red. 当我按任何单元格标签时,我需要将该标签的文本变为红色。 And other label names should be black.
其他标签名称应为黑色。
How to do that? 怎么做? I have tried the code below, but when I select any label name in that cell all the cell labels are turning red.
我已经尝试了下面的代码,但是当我在该单元格中选择任何标签名称时,所有单元格标签都变为红色。
How do I fix this? 我该如何解决?
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if let cell = collectionView1.cellForItemAtIndexPath(indexPath) {
var label = cell.viewWithTag(100) as? UILabel
label!.textColor = UIColor.redColor()
}
}
Your label doesn't update because you need to refresh cells. 您的标签不会更新,因为您需要刷新单元格。 So best solution I could offer you - change your label color in
setSelected
method in your custom cell's class 我可以为您提供最好的解决方案 - 在自定义单元格类的
setSelected
方法中更改标签颜色
Edit: 编辑:
override var setSelected(selected: bool) {
if (selected) {
self.youLabel!.textColor = UIColor.redColor()
} else {
self.youLabel!.textColor = UIColor.blackColor()
}
This is example of function in your custom class. 这是您的自定义类中的函数示例。 Sorry, if there are mistakes - answered from iPhone
对不起,如果有错误 - 从iPhone回答
Swift 4 : 斯威夫特4 :
In your cell class: 在你的细胞类中:
override var isSelected: Bool {
didSet {
label.textColor = .red
}
}
And from the delegate class: 并从代表类:
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
cell.isSelected = true
}
i created with your code, it is working to me. 我用你的代码创建,它对我有用。 but i think, it is better to create with custom collectionview cell.
但我认为,最好使用自定义collectionview单元格进行创建。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.