selectedBackgroundView修改contentView子视图
我使用自定义backgroundView
和selectedBackgroundView
UITableViewCell
子类。 这些单元格是在一个分组表,所以我设置背景和select背景作为UIImageView
s基于单元格的cellForRowAtIndexPath:
行。
我遇到的问题是,当单元格被选中时,其selectedBackgroundView
修改contentView
的内容。 例如,在select和/或突出显示一个单元格后, contentView
的UILabel
具有其backgroundColor
更改,并且用作单元格分隔符的UIView
不可见。
select之前: select后:
我没有看到这种行为logging在任何地方。 有什么我需要做的,以防止这种情况? 是否有不同的方法来显示细胞select/突出显示,我应该采取防止这一点?
- 注意:由于它是一个分组表格视图,因此我使用
UIImageView
设置了不同的backgroundView
和selectedBackgroundView
,以解决cellForRowAtIndexPath:
中的部分顶部和底部单元格上的圆angular问题,但是在使用默认值UITableViewSelectionStyleBlue
。
编辑1:
根据an0的回答,我把它setHighlighted:animated:
。 我不确定这个实现有多可靠,但是这种方法能够保持子视图的highlighted
和backgroundColor
属性:
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时自动执行两件事:
- 将所有子视图的
backgroundColor
为清除颜色(透明)。 - 突出显示可以突出显示的所有子视图,例如
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. } }
- 设置
cell.selectionStyle = UITableViewCellSelectionStyleNone
- 覆盖
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated { if(highlighted){ self.contentView.backgroundColor = colorYouWantWhenHighlighted; }else{ self.contentView.backgroundColor = colorYouWantWhenUnhighlighted; } }
在我的情况下,我有我的UITableViewCell
的背景颜色被清除的两个button。 这些button是GrayButton
types的,这是我编写的派生UIButton
的自定义类。 而不是重写UITableViewCell
方法,而不是重写GrayButton
的setBackgroundColor:
方法:
- (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];
现在只有当您点击并开始滚动的单元格不是所选单元格时,问题才可见。