![](/img/trans.png)
[英]Change label color when collectionView Cell is selected in Swift iOS
[英]How to change label text color and image in prototype cell programmatically when cell selected in iOS
我面临一个奇怪的问题。 我在Storyboard中有一个tableview控制器,带有5个原型单元。 每个单元格都有一个标签和一个图像。 我正在尝试以编程方式选择单元格时更改标签和图像的文本颜色,如下所示。
In cellForRowAtIndexPath method
{
// Using tags I am getting labels from storyboard.
label1 = (UILabel *)[cell.contentView viewWithTag:101];
label2= (UILabel *)[cell.contentView viewWithTag:102];
label3 = (UILabel *)[cell.contentView viewWithTag:103];
label4 = (UILabel *)[cell.contentView viewWithTag:104];
label5 = (UILabel *)[cell.contentView viewWithTag:105];
label1.textColor =[UIColor blackColor];
label2.textColor =[UIColor blackColor];
label3.textColor =[UIColor blackColor];
label4.textColor =[UIColor blackColor];
label5.textColor =[UIColor blackColor];
}
在didSelectRowAtIndexPath方法中
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
label1 = (UILabel *)[cell.contentView viewWithTag:101];
label2 = (UILabel *)[cell.contentView viewWithTag:102];
label3 = (UILabel *)[cell.contentView viewWithTag:103];
label4 = (UILabel *)[cell.contentView viewWithTag:104];
label5 = (UILabel *)[cell.contentView viewWithTag:105];
在这里,我想将选中的标签文本颜色更改为白色,否则应为黑色。 选中时,我可以将文本颜色更改为白色,但是如果选择其他单元格,则无法将文本颜色设置为黑色。
在didDeselectRowAtIndexPath
您可以将颜色更改回黑色。
使用UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
得到细胞。
为什么不创建UITableViewCell子类并覆盖setSelected:animated:
和setHighlighted:animated:
在这里,您可以更新标签的颜色并轻松更改图像。 在这样的示例中:
- (void)setSelected:(BOOl)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
_label.textColor = (selected ? _selectedColor : _unselectedColor);
}
您可以更改单元子类使用身份标识检查器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.