【问题标题】:iOS: Background Color -- UITableView and Accessory to have same background coloriOS:背景颜色——UITableView 和附件具有相同的背景颜色
【发布时间】:2023-03-03 09:38:01
【问题描述】:

我有一个 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]?

【问题讨论】:

    标签: ios objective-c uitableview uisearchbar


    【解决方案1】:

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

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

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

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

    - (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];这适用于我的情况,我假设大多数人可能会同意你的回答。如果您还可以包含一个代码来跟踪所选单元格,我想将您的答案标记为正确。
    • 对,我假设您希望使用自定义颜色绘制单元格,但正如您指出的灰色 [cell setSelectionStyle:UITableViewCellSelectionStyleGray]; 也可以:-)
    • 虽然问题是选择一个单元格,但我多次遇到这个附件视图问题!为了解决这个问题,我对它进行了子类化并绘制了一个类似的人字形。这个解释,加上惊人的图表,帮了我很大的忙。肯定+1。谢谢@andreagiavatto!
    猜你喜欢
    • 2015-11-01
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多