UITableViewCell权限控制选中+设置selectedBackgroundView后UILabel背景异常
解决UITableViewCell选中时UILabel背景变透明的问题
你遇到的这个问题我很熟悉,咱们来一步步排查解决:
问题根源
你当前对可选中单元格的处理是设置了一个透明背景的selectedBackgroundView:
UIView *customView = [[UIView alloc] initWithFrame:cell.frame]; customView.backgroundColor = [UIColor clearColor]; cell.selectedBackgroundView = customView;
当单元格被选中时,这个透明视图会覆盖在cell上层,而如果你的UILabel没有显式设置固定背景色,就会继承这个透明属性,看起来就变成了透明色。
三种可行解决方案
方案一:直接给UILabel设置固定背景色
在配置cell内容的环节,给所有需要保持背景的UILabel显式设置和cell一致的黑色背景:
// 放在设置label文本的代码之后 cell.projectName.backgroundColor = [UIColor blackColor]; cell.projectNumber.backgroundColor = [UIColor blackColor]; cell.owner.backgroundColor = [UIColor blackColor]; cell.date.backgroundColor = [UIColor blackColor]; cell.serial.backgroundColor = [UIColor blackColor];
这样不管cell处于选中还是常态,label的背景色都固定为黑色,不会被选中状态影响。
方案二:在cell子类中重写选中状态处理方法
把cell的状态逻辑封装在EditProjectTableCell子类里,重写setSelected:animated:方法:
- (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; // 强制保持contentView的背景色为黑色,覆盖选中状态的影响 self.contentView.backgroundColor = [UIColor blackColor]; // 也可以单独给每个label设置背景色,效果一致 // self.projectName.backgroundColor = [UIColor blackColor]; // ...其他label同理 }
这种方式更符合MVC设计原则,把cell的UI状态管理放在自己的类里。
方案三:调整选中背景视图的颜色
既然cell常态背景是黑色,不如让选中背景也用黑色,而不是透明:
if ([project.role isEqualToString:@"1"] || [project.role isEqualToString:@"2"]) { // 注意用cell.bounds替代frame,避免布局偏移问题 UIView *customView = [[UIView alloc] initWithFrame:cell.bounds]; customView.backgroundColor = [UIColor blackColor]; cell.selectedBackgroundView = customView; } else { cell.selectionStyle = UITableViewCellSelectionStyleNone; }
这样选中时的背景和常态一致,既保留了选中功能,又不会出现透明问题。
另外提个小细节:你创建selectedBackgroundView时用了cell.frame,换成cell.bounds会更稳妥,因为bounds是cell自身的坐标系统,避免因父视图布局导致的偏移。
内容的提问来源于stack exchange,提问作者Rashad
相关产品推荐
相关产品推荐

