UITableViewCellselect行的文本颜色更改

我有一个tableview,我想知道如何更改选定的行的文本颜色,说红? 我试过这个代码:

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

(1)当我select任何行时,文本颜色变成红色,但是当我select另一行时,先前select的行文本保持红色。 我怎么解决这个问题?

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

谢谢..

tableView:cellForRowAtIndexPath:执行此操作

 cell.textLabel.highlightedTextColor = [UIColor redColor]; 

(并且不要再使用cell.text = ...现在已经使用了近2年,请使用cell.textLabel.text = ... )。


正如Raphael Oliveira在评论中提到的,如果你的单元格的selectionStyle等于UITableViewCellSelectionStyleNone这将不起作用。 检查故事板以及select风格。

如果只想更改文字颜色,不更改单元格背景颜色。 你可以使用this.Write这个代码在cellForRowAtIndexPath方法

 UIView *selectionColor = [[UIView alloc] init]; selectionColor.backgroundColor = [UIColor clearColor]; cell.selectedBackgroundView = selectionColor; cell.textLabel.highlightedTextColor = [UIColor redColor]; 

如果你已经创build了UITableViewCell子类,那么设置awakeFromNib方法中的颜色(假设你正在从storyboard或xib实例化)更容易/更清晰。

 @implementation MySubclassTableViewCell - (void)awakeFromNib { [super awakeFromNib]; self.selectedBackgroundView = [[UIView alloc] initWithFrame:self.frame]; self.selectedBackgroundView.backgroundColor = [UIColor colorWithRed:0.1 green:0.308 blue:0.173 alpha:0.6]; self.customLabel.highlightedTextColor = [UIColor whiteColor]; } @end 

我有同样的问题,试试这个!

 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; for (id object in cell.superview.subviews) { if ([object isKindOfClass:[UITableViewCell class]]) { UITableViewCell *cellNotSelected = (UITableViewCell*)object; cellNotSelected.textLabel.textColor = [UIColor blackColor]; } } cell.textLabel.textColor = [UIColor redColor]; [tableView deselectRowAtIndexPath:indexPath animated:NO]; } 

这可能是解决您(和我)的问题。