views:

311

answers:

1

I have a UITableViewCell with the UITableViewStyleGrouped style and I would like to change the background color of the cell.

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)ip {
    // Do cell creation stuff ...

    cell.backgroundColor = 
      [UIColor colorWithRed:255.0/255.0 green:243.0/255.0 blue:175.0/255.0 alpha:0.50];
}

The trouble is, this doesn't display properly on a grid with the UITableViewStyleGrouped; I use the same color on a UITableViewStylePlain and it displays correctly. I'm developing for OS 3.0 and have read the multiple posts on setting background color. I can set the color it just doesn't set properly! What am I missing?

Incorrect yellow background with Alpha Correct yellow background with Alpha

A: 

You must be doing something in your cell creation/reuse logic to change the default behavior. Starting a project from scratch and implementing this code works for me:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.
    cell.backgroundColor = [UIColor colorWithRed:1.0 green:0 blue:0 alpha:1.0];

    return cell;
}

Double check the documentation if you need something more complex.

Also, could the color shift be coming because of the different table background colors in the two different styles? A UITableViewStylePlain tableView has a default white background. A UITableViewStyleGrouped tableView will have a gray background. Since your are setting the alpha to 0.5, it will overlay onto two different color backgrounds and give you a color shift.

Chip Coons
@Chip - Thanks for the answer, I'll give it a try and see what happens. I think you might be right about the overlay on the gray background color. If that's the problem is there a solution for that?
Gavin Miller
If that's the issue, subclass the UITableViewCell. You can then make "solid background cell" white and have a colored background with alpha in front of it. Alternatively, if transparency is not really needed, figure out the opaque color of the cell and just set it.
Chip Coons