Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Background Color -- UITableView and Accessory to have same background color

I have a UISearchBar. When I select the cell, I'd like the entire cell to have a [UIColor grayColor];

With the code below, the contentView color appears Gray; however, the background accessoryType color shows up 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 do I make the Blue appear also as [UIColor grayColor]?

like image 263
user1107173 Avatar asked Apr 19 '13 19:04

user1107173


1 Answers

You are changing the background color of the content view which is just a portion of the cell view.

UITableViewCell representation

Change the background color of the entire cell. However you can't do that in your tableView:didDeselectRowAtIndexPath: because it won't work as explained here.

Note: If you want to change the background color of a cell (by setting the background color of a cell via the backgroundColor property declared by UIView) you must do it in the tableView:willDisplayCell:forRowAtIndexPath: method of the delegate and not in tableView:cellForRowAtIndexPath: of the data source.

In your case, keep track of the row selected in your tableView:didSelectRowAtIndexPath: by saving the index in an ivar and reloading the table view.

- (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];
    }  
}
like image 97
andreag Avatar answered Oct 12 '22 16:10

andreag