Jun 13

When we work with table (UITableView), we can build custom cells with Interface Builder and load them, o build them directly from the code. The problem appears when we change the background color for the custom cell, but don’t do the same when there are empty cells on screen.

We can see something like this.

This happens cause we only make the cells while we have data but may be more cells in screen than data to show. We have two solutions:

  • Prepare our code to take into account both cases, changing the background color when there is no data but put away any other element of the custom cell.
  • Change the background color in all cells, before we take into account anything else.

With the second solution it’s faster, we need to do this in code, as Interface Builder doesn’t let us get to where we need only adding a table.

We need to add only a line to our code

// Customize the appearance of table view cells.
- (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 contentView] setBackgroundColor:[UIColor colorWithRed:0 green:128/255.f blue:0 alpha:1]];
    return cell;

The important line is the one where we call the method setBackgroundColor:, with this line we change the color but notice that we change the background color for [cell contentView], we have to change the contentView and this is way we can’t do this from Interface Builder, it won’t let us change the background of the cells, only the background of the table view.

We get now something like this

VN:F [1.9.8_1114]
Rating: 5.0/5 (2 votes cast)
VN:F [1.9.8_1114]
Rating: +1 (from 1 vote)
Background color of empty cells, 5.0 out of 5 based on 2 ratings

Leave a Reply

You must be logged in to post a comment.

preload preload preload