Maurizio
Maurizio

Reputation: 4169

Custom UITableViewCell background goes transparent after selection

When selecting, and holding, one of my custom cells for a UITableView plain-style table, it displays my custom selection color (redColor in this case), but then if I keep it held down and scroll, the custom selection color and the custom background disappear (showing through to the UIImageView behind the table.

The UITableView is created in IB and has a background set to clearColor to allow an image to show through.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];

    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                         reuseIdentifier:kCellIdentifier] 
                autorelease];

        cell.selectionStyle = UITableViewCellSelectionStyleBlue;

        /* Background */
        cell.backgroundView = [[[UIImageView alloc] init] autorelease];
        cell.selectedBackgroundView = [[[UIImageView alloc] init] autorelease];
    }

    cell.backgroundView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"customBackground"]];
    cell.selectedBackgroundView.backgroundColor = [UIColor redColor];

    return cell;
}

Can anyone help? Thanks!

Upvotes: 3

Views: 1463

Answers (1)

Maurizio
Maurizio

Reputation: 4169

Ok I solved this. Basically you cannot use initWithPatternImage when customizing a UITableViewCell. After it is selected, it's background view must either go transparent, or be removed from the view hierarchy.

Use the following:

((UIImageView*)cell.backgroundView).image = [UIImage imageNamed:@"customBackground"];
((UIImageView*)cell.selectedBackgroundView).image = [UIImage imageNamed:@"selectedBackground"];

Upvotes: 4

Related Questions