UITableViewCell选择了行的文本颜色更改

Mau*_*lik 61 iphone objective-c uitableview ios

我有一个tableview,我想知道如何更改所选行的文本颜色,比如Red?我试过这段代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell= [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];

    cell.text = [localArray objectAtIndex:indexPath.row];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    cityName = [localArray objectAtIndex:indexPath.row];

    UITableViewCell* theCell = [tableView cellForRowAtIndexPath:indexPath];
    theCell.textColor = [UIColor redColor];
    //theCell.textLabel.textColor = [UIColor redColor];

    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}
Run Code Online (Sandbox Code Playgroud)

(1)当我选择任何行时,文本颜色变为红色,但当我选择另一行时,之前选择的行的文本保持红色.我该怎么解决这个问题?

(2)当我滚动表格文字颜色变为黑色时如何解决这个问题?

谢谢..

Ole*_*ann 203

这样做tableView:cellForRowAtIndexPath::

cell.textLabel.highlightedTextColor = [UIColor redColor];
Run Code Online (Sandbox Code Playgroud)

(并且不再使用cell.text = ...了.现在已经被弃用了近2年.请cell.textLabel.text = ...改用.)


正如拉斐尔奥利维拉在评论中提到的,如果你的细胞的selectionStyle等于UITableViewCellSelectionStyleNone这将是行不通的.检查故事板以及选择样式.

  • 值得一提的是,如果你的单元格的selectionStyle等于UITableViewCellSelectionStyleNone,这将无效.你可能没有添加这个代码,但检查故事板,不要​​浪费很多时间,比如我试图弄清楚为什么这不起作用. (7认同)

Rin*_*nku 5

如果您只想更改文本颜色,而不更改单元格背景颜色。你可以使用这个。将此代码写入 cellForRowAtIndexPath 方法

UIView *selectionColor = [[UIView alloc] init];
selectionColor.backgroundColor = [UIColor clearColor];
cell.selectedBackgroundView = selectionColor;
cell.textLabel.highlightedTextColor = [UIColor redColor];
Run Code Online (Sandbox Code Playgroud)