UITableViewCell高亮(按下)时,子视图背景色变透明的解决方法

UITableViewCell highlighted subviews backgroundColor


自定义的UITableViewCell,在上面添加一个UIView(这里是UILabel),设置UILabel背景色。但是当cell处于按下状态时,UILabel背景色就会消失。如图(选中行的(2)背景色消失):

UITableViewCell高亮(按下)时,子视图背景色变透明的解决方法_第1张图片


其实这个问题的原因可以在文档里找到,(大意)当cell处于highlighted/selected状态时,默认会执行如下动作:

1:将其所有子视图的backgroundColor设置为清除颜色(透明)。

2:突出显示可以突出显示的所有子视图内容(就是强调内容),例如UIImageView。


想要让消失的UILabel背景色回来,只要解决第一个问题即可。

解决方法:

重载自定义cell的highlighted方法(是否重载selected看你需要),需要注意设置:

cell.selectionStyle = UITableViewCellSelectionStyleNone;

否则cell高亮时还是会执行系统默认动作。

//由于numLabel修改了背景颜色,所以高亮需要自己处理
//注意:cell的selectionStyle必须是:UITableViewCellSelectionStyleNone;否则无效
-(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
{
    [super setHighlighted:highlighted animated:animated];
    //动画高亮变色效果
    [UIView animateWithDuration:0.3 animations:^{
        if(highlighted)
            self.contentView.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1];
        else
            self.contentView.backgroundColor = [UIColor whiteColor];
    }];
}

这样问题就解决了。


转载请注明出处:http://blog.csdn.net/cuibo1123

=======

UITableViewCell高亮(按下)时,子视图背景色变透明的解决方法_第2张图片

欢迎加我微信探讨问题:lofocus



你可能感兴趣的:(iOS开发)