UITableView单元格textLabel颜色

时间:2012-03-16 07:08:21

标签: ios objective-c iphone uitableview

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

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

如果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;
}

它可以工作,但在滚动tableview时,颜色会变回。

3 个答案:

答案 0 :(得分:20)

得到了解决方案 通过在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];

}

由于

答案 1 :(得分:14)

你所要做的就是

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

if if(cell == nil)

可行。

答案 2 :(得分:0)

设置全局:int m_selectedCell;

中修改它
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

只需添加

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

in

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

就是这样!

相关问题