如何让UITableViewCell
中的自定义子图层在setSelected:animated:
中消失?
上下文
我通过在UITableViewCell
内添加CAGradientLayer
向我的drawRect:
添加了自定义背景图层,如下所示:
- (void)drawRect:(CGRect)rect{
[super drawRect:rect];
[[self providerLabel] setTextColor:kOUBlue];
[self addGrayLayer];
}
- (void)addGrayLayer{
[[[self contentView] layer] insertSublayer:[self grayGradientLayer] atIndex:0];
}
- (CAGradientLayer *) grayGradientLayer{
if (!_grayGradientLayer) {
CAGradientLayer *gradient = [CAGradientLayer layer];
UIColor *white = [UIColor colorWithWhite:1 alpha:2];
UIColor *gray = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
[gradient setColors:@[(id)white.CGColor, (id)gray.CGColor]];
[gradient setFrame:[self bounds]];
_grayGradientLayer = gradient;
}
return _grayGradientLayer;
}
当用户点按某个单元格时,不会显示蓝色突出显示。所以我试图隐藏CAGradientLayer
中的setSelected:animated:
,如此:
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
if (selected) {
[[self grayGradientLayer] setHidden:YES];
}else{
[[self grayGradientLayer] setHidden:NO];
}
[[self contentView] setNeedsDisplay];
}
出现蓝色背景,但直到推动动画开始。有没有办法让我立即出现默认蓝色?我还尝试添加第二个彩色CAGradientLayer
并手动交换它们,但在我看来,在setSelected:
隐藏图层后,单元格不会立即重绘。
我试图使用setNeedsDisplay
强制重绘单元格,但没有运气。有什么想法吗?
答案 0 :(得分:0)
在挖掘之后,我found this question,我意识到我使用了错误的方法。事实证明我必须使用setHighlighted:animated:
方法。
我的新代码如下:
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
[super setHighlighted:highlighted animated:animated];
if (highlighted) {
[[self grayGradientLayer] setHidden:YES];
}else{
[[self grayGradientLayer] setHidden:NO];
}
}