开发者

Custom UITableViewCell background goes transparent after selection

开发者 https://www.devze.com 2023-01-23 10:31 出处:网络
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

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 selec开发者_运维技巧tion 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!


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"];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号