0
votes

I have always been setting the background of my UITableViewCell inside the cellForRowAtIndexPath call, like this:

CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:simple];

if (cell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];

    for (id findCell in nib )
    {
        if ( [findCell isKindOfClass: [CustomCell class]])
        {
            cell = findCell;
        }    
    }

    UIView *cellBackView = [[UIView alloc] initWithFrame:CGRectZero];
    UIView *cellSelectedBackView = [[UIView alloc] initWithFrame:CGRectZero];

    if (UIUserInterfaceIdiomPad == UI_USER_INTERFACE_IDIOM()) {

        cellBackView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"cell_shadows_ipad_light.png"]];
        cellSelectedBackView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"blue_cell.png"]];
    }else {
        cellBackView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"cell_shadows.png"]];
        cellSelectedBackView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"blue_cell.png"]];
    }

    cell.backgroundView = cellBackView;
    cell.selectedBackgroundView = cellSelectedBackView;

Now I've discovered that there's another way to achieve this, which is to set the background views inside this delegate:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
   // load the background image and set it as the background color as above
}

And since iOS5, you can just register the nib with the tableView, so I don't need to cycle through to find the class nib either. So, in viewDidLoad:

[self.tableView registerNib:[UINib nibWithNibName: @"CustomCellSplit" bundle:nil] forCellReuseIdentifier: @"CustomCellId"];

So this works, it's simpler, and it is the Apple-recommended way of loading the cell's nib and setting the background view. However, what I've found is that this tableView: willDisplayCell: forRowAtIndexPath is called for each row as you scroll through the list. With the way I loaded the background view previously, it would only set the backgroundView when the cells were created (8 or 10 times at most).

So the new way sounds like a less-performant way of loading up the cells and setting the backgroundViews. Is this the right assumption, or am I missing something here?

1

1 Answers

1
votes

Turns out it's really simple. You just add a subview in the nib and connect it to the selectedBackgroundView outlet in the UITableViewCell.

http://cl.ly/image/322L2k3j2U1Aconnecting selectedBackgroundView outlet from nib

Voila.

iOS5 is smart enough to remove the backgroundView from the cell's contentView in runtime.

No need to use the tableView:willDisplayCell function.