Need to change the color of table view selection

smakstr picture smakstr · Sep 28, 2009 · Viewed 23.9k times · Source

I need to change the default blue color selection of table view to some custom color. Is there any way to do that. Help me

Answer

Zoran Simic picture Zoran Simic · Sep 28, 2009

The best way to do this is like this:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"myCellId";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        UIView *v = [[[UIView alloc] init] autorelease];
        v.backgroundColor = [UIColor redColor];
        cell.selectedBackgroundView = v;
    }
    // Set up the cell...
    cell.textLabel.text = @"foo";
    return cell;
}

The relevant part for you is the cell.selectedBackgroundView = v; instruction. You can substitute the very basic view 'v' here with any view you like.