5

我有一个 UISearchBar。当我选择单元格时,我希望整个单元格都有一个 [UIColor grayColor];

使用下面的代码,contentView 颜色显示为灰色;但是,背景附件类型颜色显示为蓝色:

在此处输入图像描述

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

UITableViewCell *cell = [self.searchDisplayController.searchResultsTableView cellForRowAtIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor grayColor];

    if (self.lastSelected && (self.lastSelected.row == indexPath.row))
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
        [cell setSelected:NO animated:TRUE];
        self.lastSelected = nil;
    } else {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        cell.accessoryView.backgroundColor = [UIColor grayColor]; // Not working
        [cell setSelected:TRUE animated:TRUE];

        UITableViewCell *old = [self.searchDisplayController.searchResultsTableView cellForRowAtIndexPath:self.lastSelected];
        old.accessoryType = UITableViewCellAccessoryNone;
        [old setSelected:NO animated:TRUE];
        self.lastSelected = indexPath;
    }

如何使蓝色也显示为 [UIColor grayColor]?

4

1 回答 1

10

您正在更改内容视图的背景颜色,它只是单元格视图的一部分。

UITableViewCell 表示

更改整个单元格的背景颜色。但是,您不能这样做,tableView:didDeselectRowAtIndexPath:因为它不会像这里解释的那样工作。

注意:如果要更改单元格的背景颜色(通过 UIView 声明的 backgroundColor 属性设置单元格的背景颜色),您必须在tableView:willDisplayCell:forRowAtIndexPath:委托的方法中进行,而不是在tableView:cellForRowAtIndexPath:数据源中进行。

tableView:didSelectRowAtIndexPath:在您的情况下,通过将索引保存在 ivar 中并重新加载表视图来跟踪您选择的行。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    _savedIndex = indexPath;
    [tableView reloadData];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([_savedIndex isEqual:indexPath]) {
         cell.backgroundColor = [UIColor grayColor];
    }  
}
于 2013-04-19T20:31:27.770 回答