我有一个自定义的 UITableViewController
,它只有一行,只有两个 UITableViewCell
。
我正在尝试根据以下几点动态设置 UITableViewCell
文本的颜色 (cell.textLabel.textColor
):
1) 如果这是第一次启动,第一个单元格的文本颜色应该是[UIColor whiteColor]
,第二个单元格的文本颜色应该是[UIColor grey1Color]
2) 如果用户选择一个单元格并离开屏幕然后返回到表格 View ,最后选择的单元格的文本颜色应该是[UIColor whiteColor]
,并且单元格的文本颜色未选中的应为 [UIColor grey1Color]
。
每当选择一个单元格时,都会更新一个属性; 我的单元格文本值
。这样做是为了在这个特定的 TableView 之外进行一些 API 调用。
我实现上述逻辑的想法是使用此属性来确定单元格文本的颜色。我下面的代码尝试在 cellForRowAtIndexPath
中:
if (cell.textLabel.text == self.myCellTextValue) {
cell.textLabel.textColor = [UIColor whiteColor];
} else {
cell.textLabel.textColor = [UIColor grey1Color];
}
}
但是,两个单元格的文本颜色始终为灰色。我确信这主要与在某种程度上误解 UITableViewCell
创建有关。有没有人对如何正确实现有任何指示?谢谢!
编辑:按照下面@Gismay 的评论,我尝试了下面的代码;但得到了相同的结果:
if ([cell.textLabel.text isEqualToString:self.myCellTextValue]) {
cell.textLabel.textColor = [UIColor whiteColor];
} else {
cell.textLabel.textColor = [UIColor grey1Color];
}
编辑 2:我还尝试将上面的代码包装在一个检查中,以确保我们一次只查看一个单元格,但这也没有效果:
if((indexPath.section==0)&&(indexPath.row==0)){
if ([cell.textLabel.text isEqualToString:self.myCellTextValue]) {
cell.textLabel.textColor = [UIColor whiteColor];
} else {
cell.textLabel.textColor = [UIColor grey1Color];
}
} else if((indexPath.section==0)&&(indexPath.row==1)){
if ([cell.textLabel.text isEqualToString:self.myCellTextValue]) {
cell.textLabel.textColor = [UIColor whiteColor];
} else {
cell.textLabel.textColor = [UIColor grey1Color];
}
}
最佳答案
你可以这样做:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//change your cell text color here
cell= [tableView cellForRowAtIndexPath:indexPath]
cell.textLabel.textColor = [UIColor whiteColor];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (cell.isSelected == YES)
{
cell.textLabel.textColor = [UIColor grey1Color];
}
else
{
cell.textLabel.textColor = [UIColor whiteColor];
}
}
另一种方法是子类化 tableview 单元格并实现以下方法:
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
[self updateTextColor:selected];
}
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
[super setHighlighted:highlighted animated:animated];
[self updateTextColor:highlighted];
}
- (void)updateTextColor:(BOOL)isSelected {
labelA= //get reference of the cell textlabel
if (labelA) {
if (isSelected) {
[labelA setTextColor:[UIColor whiteColor]];
} else {
[labelA setTextColor:[UIColor greyColor]];
}
}
}
关于ios - 动态改变 UITableViewCell 文本的 textColor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35876093/