selectedBackgroundView修改contentView子视图

我使用自定义backgroundViewselectedBackgroundView UITableViewCell子类。 这些单元格是在一个分组表,所以我设置背景和select背景作为UIImageView s基于单元格的cellForRowAtIndexPath:行。

我遇到的问题是,当单元格被选中时,其selectedBackgroundView修改contentView的内容。 例如,在select和/或突出显示一个单元格后, contentViewUILabel具有其backgroundColor更改,并且用作单元格分隔符的UIView不可见。

select之前: 选择/突出显示之前 select后: 选择/高亮后

我没有看到这种行为logging在任何地方。 有什么我需要做的,以防止这种情况? 是否有不同的方法来显示细胞select/突出显示,我应该采取防止这一点?

  • 注意:由于它是一个分组表格视图,因此我使用UIImageView设置了不同的backgroundViewselectedBackgroundView ,以解决cellForRowAtIndexPath:中的部分顶部和底部单元格上的圆angular问题,但是在使用默认值UITableViewSelectionStyleBlue

编辑1:

根据an0的回答,我把它setHighlighted:animated: 。 我不确定这个实现有多可靠,但是这种方法能够保持子视图的highlightedbackgroundColor属性:

 NSArray *recursiveAllSubviews = [self recursiveValueForKey:@"subviews"]; // Uses MTRecursiveKVC Cocoapod NSArray *backgroundColors = [recursiveAllSubviews valueForKey:@"backgroundColor"]; [super setHighlighted:highlighted animated:animated]; if (highlighted) { [recursiveAllSubviews enumerateObjectsUsingBlock:^(UIView *view, NSUInteger index, BOOL *stop){ if ([view respondsToSelector:@selector(setHighlighted:)]) { [view setValue:[NSNumber numberWithBool:NO] forKey:@"highlighted"]; } id possiblyNull = [backgroundColors objectAtIndex:index]; if (possiblyNull != [NSNull null]) { view.backgroundColor = possiblyNull; } }]; } 

UITableViewCell在突出显示/select时自动执行两件事:

  1. 将所有子视图的backgroundColor为清除颜色(透明)。
  2. 突出显示可以突出显示的所有子视图,例如UIImageView

为了防止第一个问题,你必须在你的UITableViewCell子类中重写这两个方法:

 - (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated { [super setHighlighted:highlighted animated:animated]; if (highlighted) { // Recover backgroundColor of subviews. } } - (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; if (selected) { // Recover backgroundColor of subviews. } } 
  1. 设置cell.selectionStyle = UITableViewCellSelectionStyleNone
  2. 覆盖

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated { if(highlighted){ self.contentView.backgroundColor = colorYouWantWhenHighlighted; }else{ self.contentView.backgroundColor = colorYouWantWhenUnhighlighted; } }

在我的情况下,我有我的UITableViewCell的背景颜色被清除的两个button。 这些button是GrayButtontypes的,这是我编写的派生UIButton的自定义类。 而不是重写UITableViewCell方法,而不是重写GrayButtonsetBackgroundColor:方法:

 - (void)setBackgroundColor:(UIColor *)backgroundColor { if (backgroundColor != [UIColor clearColor]) { [super setBackgroundColor:backgroundColor]; } } 

在我的情况下,我切换到contentView,它效果更好

 UIColor *backgroundColor = selected ? [UIColor redColor] : [UIColor clearColor]; self.contentView.backgroundColor = backgroundColor; 

而不是replaceselectedBackgroundView

  UIView *selectionColor = [[UIView alloc] init]; selectionColor.backgroundColor = selected ? [UIColor redColor] : [UIColor clearColor];; self.selectedBackgroundView = selectionColor; [selectionColor release]; 

现在只有当您点击并开始滚动的单元格不是所选单元格时,问题才可见。