简体   繁体   English

UITableView单元格textLabel颜色

[英]UITableView cell textLabel color

I have a simple issue with UITableViewCell . 我有一个UITableViewCell的简单问题。 What I want is to change the text color of a selected cell. 我想要的是更改所选单元格的文本颜色。 In my cellForRowAtIndexPath method, I set: 在我的cellForRowAtIndexPath方法中,我设置:

cell.textLabel.textColor = [UIColor whiteColor];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.highlightedTextColor = [UIColor orangeColor];

If the selectionStyle is UITableViewCellSelectionStyleNone , highlightedTextColor will not change. 如果selectionStyleUITableViewCellSelectionStyleNone ,则highlightedTextColor不会改变。 So I use these two methods to set the text color: 所以我使用这两种方法来设置文本颜色:

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  [tableView cellForRowAtIndexPath:indexPath].textLabel.textColor = [UIColor orangeColor];    
  return indexPath;
}
- (NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
  [tableView cellForRowAtIndexPath:indexPath].textLabel.textColor = [UIColor whiteColor];    
  return indexPath;
}

It works, but when scrolling the tableview, the color changes back. 它有效,但滚动tableview时,颜色会变回。

Got the solution by setting color in if (cell == nil) check 通过在if(cell == nil)检查中设置颜色来获得解决方案

if (cell == nil) 
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    cell.textLabel.textColor = [UIColor whiteColor];  
}     

and

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    [tableView cellForRowAtIndexPath:indexPath].textLabel.textColor = [UIColor orangeColor];

}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
        [tableView cellForRowAtIndexPath:indexPath].textLabel.textColor = [UIColor whiteColor];

}

Thanks 谢谢

All that you have to do is 你所要做的就是

cell.textLabel.textColor = [UIColor whiteColor];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.highlightedTextColor = [UIColor orangeColor];

inside if(cell == nil) 在if if(cell == nil)

that will work fine. 这将很好。

set a global : int m_selectedCell; 设置全局: int m_selectedCell; modify it in 修改它

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

and

just add 加上

if(m_selectedCell == indexPath.row){
...
...
}else{
}

in

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath 

that's all ! 就这样 !

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

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