0

如何在UITableViewCell消失中制作自定义子图层setSelected:animated:

语境:

UITableViewCell通过添加CAGradientLayerinside 为我添加了一个自定义背景层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;
}

当用户点击单元格时,不会出现蓝色突出显示。所以我试图CAGradientLayersetSelected: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但没有成功。有任何想法吗?

4

1 回答 1

0

在挖掘之后,我发现了这个问题,我意识到我使用了错误的方法。事实证明我必须使用该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];
   }
}
于 2012-11-12T20:47:35.027 回答