【问题标题】:UITableView cell textLabel colorUITableView 单元格文本标签颜色
【发布时间】:2023-04-03 07:25:01
【问题描述】:

我对@9​​87654321@ 有一个简单的问题。 我想要的是更改选定单元格的文本颜色。 在我的cellForRowAtIndexPath 方法中,我设置了:

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

如果selectionStyleUITableViewCellSelectionStyleNonehighlightedTextColor 不会改变。 所以我用这两种方法来设置文字颜色:

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

它可以工作,但是当滚动表格视图时,颜色会变回来。

【问题讨论】:

  • 如何声明一个 NSIndexPath *urIndexPath;在你的 .h?然后在您的 didSelecteRowAtIndexPath 方法中,将所选单元格的 indexPath 传递给 urIndexPath 然后 reloadData 以更新 UI,在您的 cellForRowAtIndexPath 中,说类似,如果 urIndexPath 是 == indexPath {将颜色设置为橙色; }else{ 默认颜色是什么}
  • @Akhildas 当您滚动 tableView 时 cellForRowAtIndex: 方法将始终被调用。但不是您拥有的其他方法。更好的是您可以在“cellForRowAtIndex:”方法中调用“WillSelectRowAtIndexPath”方法以使其工作

标签: ios objective-c iphone uitableview


【解决方案1】:

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

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

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

}

谢谢

【讨论】:

    【解决方案2】:

    你要做的就是

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

    在 if(cell == nil) 内

    这样就可以了。

    【讨论】:

      【解决方案3】:

      设置全局:int m_selectedCell; 修改它

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

      只需添加

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

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

      就是这样!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多