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:
- (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]?
You are changing the background color of the content view which is just a portion of the cell view.
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 intableView: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];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With