UITableViewCell 点击,cell控件的背景颜色消失!

相信在日常的开发中,应产品与UI的要求,会自定义个漂亮的Cell,cell上面的控件五颜六色,看着让人赏心悦目啊!但是,悲催的是在点击cell的时候,所有控件的背景颜色都消失,整个cell变的灰蒙蒙的,心中顿时一群草泥马奔过!
今天,记录一下这个问题的几种解决方法,也为了以后方便自己查阅。

效果:

  • 点击前:
UITableViewCell 点击,cell控件的背景颜色消失!_第1张图片
效果图1
  • 点击时:
UITableViewCell 点击,cell控件的背景颜色消失!_第2张图片
效果图2

原因:

当点击UITableViewCell时,会使用到cell的selectionStyle属性, 属性的默认值是UITableViewCellSelectionStyleBlue,点击时会将cell上子控件的背景颜色设置为透明,所以就消失了。
我们可以将selectionStyle属性值改为cell.selectionStyle = UITableViewCellSelectionStyleNone,但是这样点击cell就没有任何效果,不能满足大部分开发者的需求。

UIImageView:

解决方法:
将颜色转换为UIImage,然后imageView.image = image。问题就解决了,其他控件如果可以设置UIImage也可以用这个方法,例如UIButton等。
UIColor转UIImage的方法:

//color转image
- (UIImage *) createImageWithColor: (UIColor *) color {
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

其他方法:

对于那些不方便设置UIImage,或只能设置背景颜色的控件来说,就需要另外一种方法了。在继承UITableViewCell的子类.m文件中,实现父类的cell按中的两个方法,在方法中设置控件的显示颜色。

//这个方法在Cell被选中或者被取消选中时调用
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    self.label.backgroundColor = [UIColor colorWithRed:69/255.0f green:144/255.0f blue:228/255.0f alpha:1];
    self.imageView.backgroundColor = [UIColor colorWithRed:69/255.0f green:19/255.0f blue:227/255.0f alpha:1];
}
//这个方法在用户按住Cell时被调用
-(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
    [super setHighlighted:highlighted animated:animated];
    self.label.backgroundColor = [UIColor colorWithRed:69/255.0f green:144/255.0f blue:228/255.0f alpha:1];
    self.imageView.backgroundColor = [UIColor colorWithRed:69/255.0f green:19/255.0f blue:227/255.0f alpha:1];
}


实践证明,UIImageView最好还是设置其image,在上面的两个方法中设置控制背景颜色无效。

你可能感兴趣的:(UITableViewCell 点击,cell控件的背景颜色消失!)