我正在尝试做一些应该非常简单的事情。我想为我的一个视图添加渐变。我可以将它添加到 self.view,但不能添加到 viewWithGradient。这是代码:
CAGradientLayer *gradient = [CAGradientLayer layer];
UIColor *colorFirst = [UIColor colorWithWhite:0.10 alpha:0.15];
UIColor *colorLast = [UIColor colorWithWhite:0.535 alpha:0.8];
NSArray *colors = [NSArray arrayWithObjects:(id)colorFirst.CGColor, colorLast.CGColor, nil];
gradient.colors = colors;
NSNumber *stopFirst = [NSNumber numberWithFloat:0.00];
NSNumber *stopLast = [NSNumber numberWithFloat:1.00];
NSArray *locations = [NSArray arrayWithObjects:stopFirst, stopLast, nil];
gradient.locations = locations;
gradient.frame = CGRectMake(0.0, viewWithGradient.frame.origin.y, viewWithGradient.frame.size.width, height_of_gradient);
[self.view.layer addSublayer:gradient]; // this works. I get a nice gradient at
// the bottom of the view, where I want it,
// but I need the gradient further down in
// my view hierarchy.
// [viewWithGradient.layer addSublayer:gradient]; // this doesn't. There
// is no visually noticeable change
// if this is uncommented and the
// above line is.
viewWithGradient 是我在 viewController (self.view) 内的主视图中的一个小视图。这个 viewWithGradient 只有一个其他视图。它是一个 UILabel,只占 viewWithGradient 面积的一半左右。它具有透明背景,但标签将其文本绘制为白色。我需要让渐变在 UILabel 下,而不是在 self.view 上,在 UILabel 上。
我目前怀疑我的框架/边界可能会使渐变脱离屏幕。有人看到我缺少的东西吗?这似乎是最简单的 CALayer 用法,我花了太多时间在上面。