Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to change background color of static table view cell on iOS 7 (iPad)

I am unable to change the background color of static UITableViewCells on iOS 7, when running on iPad device. You can easily check this with following setup:

  • Make a new universal project in Xcode 5 with two storyboards.
  • In each storyboard, put only one controller - table view controller, and set it as the initial one.
  • Put a few (e.g. 3) static cells in the table view in both controllers/storyboards.
  • Set the background color of each static cell to different colors in Interface Builder (I use red, green, and clear colors).

Now, run the app on iPhone and iPad simulators (iOS 7).

On the iPhone simulator, everything is ok;
while on the iPad simulator, all cells are colored white.

I tried to force iPad to work correctly by setting runtime properties in Interface Builder for cells:

  • backgroundColor to clear color
  • contentView.backgroundColor to clear color
  • backgroundView to nil

but nothing helps. Actually, setting the runtime property of contentView.backgroundColor will change the cell color, but it does not work with clear color (which means there is another view colored in white behind it).

It is very strange that two devices on same version of iOS produce different results. Can anyone else confirm this bug?

Does anyone have a solution to this problem, or the only way is to go for dynamic properties + setting color in cellForRowAtIndexPath? I would like to use static cells, because the nature of the problem is static.

p.s. I just realized that I forgot to try to set the backgroundView.backgroundColor runtime property to clear color, and I don't have access to a Mac at the moment. Maybe that would do the trick.

like image 630
Kovasandra Avatar asked Sep 24 '13 20:09

Kovasandra


2 Answers

Do this:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
     UIImage *pattern = [UIImage imageNamed:@"image.png"];
     [cell setBackgroundColor:[UIColor colorWithPatternImage:pattern]];  
}

Work for me on IOS7

like image 135
fabrizotus Avatar answered Oct 23 '22 06:10

fabrizotus


According to Apple's doc:

Whether you use a predefined or custom cell, you can change the cell’s background using the backgroundView property or by changing the inherited backgroundColor property. In iOS 7, cells have a white background by default; in earlier versions of iOS, cells inherit the background color of the enclosing table view. If you want to change the background color of a cell, do so in the tableView:willDisplayCell:forRowAtIndexPath: method of your table view delegate.

So no matter what color you set in tableView:cellForRowAtIndexPath:, iOS 7 changes it to white later. Just set it in tableView:willDisplayCell:forRowAtIndexPath:. Worked for me perfectly.

like image 45
Chex Avatar answered Oct 23 '22 06:10

Chex