iOS:背景颜色 - UITableView和Accessory具有相同的背景颜色

use*_*173 5 objective-c uitableview uisearchbar ios

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

使用下面的代码,contentView颜色显示为Gray; 但是,背景accessoryType颜色显示为蓝色:

在此输入图像描述

- (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;
    }
Run Code Online (Sandbox Code Playgroud)

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

and*_*tto 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];
    }  
}
Run Code Online (Sandbox Code Playgroud)