iOS UITableViewCell点击时子视图背景透明的解决方法

    在做iOS项目的开发中,UITableView控件的应用十分广泛。在进行自定义UITableViewCell时,经常遇到这样的问题:在UITableViewCell上面添加了一个有背景颜色的子视图,当用户点击UITableViewCell或者选中UITableViewCell时,Cell上的子视图发生了奇怪的变化,其背景色变透明了,如果添加在Cell上的子视图只是一个色块,那么我们看起来,这个子视图好像莫名其妙的消失了一样.
    如果设置  self.selectionStyle = UITableViewCellSelectionStyleNone;  这也能解决问题。
    但是如果要求点击cell有背景色,上面的方法就没用了。(提供设置cell的背景的方法 self.selectedBackgroundView = [[UIView alloc] initWithFrame:self.frame];         self.selectedBackgroundView.backgroundColor = [UIColor redColor]),这时候我们只需要重写cell的两个父类的两个方法,重新设置子视图的背景色即可。

//这个方法在Cell被选中或者被取消选中时调用
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    self.markLb.backgroundColor = [UIColor blueColor];
}
//这个方法在用户按住Cell时被调用
-(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
    [super setHighlighted:highlighted animated:animated];
    self.markLb.backgroundColor = [UIColor blueColor];
}

   

原文地址:https://www.cnblogs.com/weipeng168/p/6728799.html