UITableView单元格textLabel颜色

Gur*_*uru 16 iphone objective-c uitableview ios

我有一个简单的问题UITableViewCell.我想要的是更改所选单元格的文本颜色.在我的cellForRowAtIndexPath方法中,我设置:

cell.textLabel.textColor = [UIColor whiteColor];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.highlightedTextColor = [UIColor orangeColor];
Run Code Online (Sandbox Code Playgroud)

如果 selectionStyleUITableViewCellSelectionStyleNone, highlightedTextColor将不会改变.所以我使用这两种方法来设置文本颜色:

- (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;
}
Run Code Online (Sandbox Code Playgroud)

它有效,但滚动tableview时,颜色会变回.

Gur*_*uru 23

通过在if(cell == nil)检查中设置颜色来获得解决方案

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

- (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];

}
Run Code Online (Sandbox Code Playgroud)

谢谢


Dee*_*yan 14

你所要做的就是

cell.textLabel.textColor = [UIColor whiteColor];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.highlightedTextColor = [UIColor orangeColor];
Run Code Online (Sandbox Code Playgroud)

在if if(cell == nil)

这将很好.