IOS: Background color - UITableView and accessory have the same background color

I have a UISearchBar. When I select a cell, I would like the whole cell to have [UIColor grayColor];

In the code below, the color of the contentView is displayed Gray; however, the backgroundType background color is displayed as blue:

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

How to make blue appear just like [UIColor grayColor]?

+5
source share
1 answer

You change the background color in the content view, which is only part of the cell view.

UITableViewCell representation

Change the background color of the whole cell. However, you cannot do this in your own tableView:didDeselectRowAtIndexPath:because it will not work as described here .

. ( backgroundColor, UIView), 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];
    }  
}
+10

All Articles