自定义单元子图层和UITableViewCell选择

时间:2012-11-12 11:42:51

标签: iphone objective-c uitableview uikit cagradientlayer

如何让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强制重绘单元格,但没有运气。有什么想法吗?

1 个答案:

答案 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];
   }
}