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

5

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

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

enter image description here

- (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]一样呈现?

1个回答

10

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

UITableViewCell representation

更改整个单元格的背景颜色。但是,您不能在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];
    }  
}

感谢您的详细解释。虽然我找到了一个更简单的答案:[cell setSelectionStyle:UITableViewCellSelectionStyleGray]; 这对我的情况起作用,但我认为大多数人可能会同意您的答案。如果您还可以包括一段代码来跟踪所选单元格,我想将您的答案标记为正确的。 - user1107173
没错,我原以为你想要用自定义颜色来绘制单元格,但正如你所指出的那样,对于灰色 [cell setSelectionStyle:UITableViewCellSelectionStyleGray]; 也可以起作用 :-) - andreag
虽然问题是选择单元格,但我也遇到了许多次附属视图的问题!为了解决这个问题,我创建了一个子类并绘制了一个类似的 chevron。这个解释加上惊人的图表,帮助了我很多。+1 确定无疑。谢谢 @andreagiavatto! - Thawe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接