我正在使用最新的 SDK 开发一个 iOS 应用程序。
我想动态更改背景层:
#import <QuartzCore/QuartzCore.h>
@interface MyClass : UIView
{
@private
CALayer* _gradientBackground;
}
还有一些方法:
- (CALayer*)createLayerWithColor:(UIColor*)color
{
CALayer* layer = [CALayer layer];
layer.frame = CGRectMake(NSLayerX, NSLayerY,
NSLayerWidth, NSLayerHeight);
layer.backgroundColor = [color CGColor];
layer.cornerRadius = NSCornerRadius;
return layer;
}
- (CAGradientLayer*)createLayerWithGradient:(UIColor*)startColor
endColor:(UIColor*)endColor
{
CAGradientLayer* gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = CGRectMake(NSLayerX, NSLayerY,
NSLayerWidth, NSLayerHeight);
gradientLayer.colors =
[NSArray arrayWithObjects:(id)[startColor CGColor],
(id)[endColor CGColor], nil];
gradientLayer.cornerRadius = NSCornerRadius;
return gradientLayer;
}
- (void)changeBackgroundWithLayer:(CALayer*)newLayer
{
if (_gradientBackground != nil)
[_gradientBackground removeFromSuperlayer];
_gradientBackground = newLayer;
[self.layer insertSublayer:newLayer atIndex:0];
}
我这样做是为了改变背景层:
[self changeBackgroundWithLayer:[self createLayerWithGradient:startColor endColor:endColor]];
有时这样:
[self changeBackgroundWithLayer:[self createLayerWithColor:newColor]];
我的做法是:第一个实心层,下一个渐变层,最后是实心层。
我也试过这段代码没有结果:
- (void)changeBackgroundWithLayer:(CALayer*)newLayer
{
if (_gradientBackground != nil)
[self.layer replaceSublayer:_gradientBackground with:newLayer];
else
[self.layer insertSublayer:newLayer atIndex:0];
_gradientBackground = newLayer;
}
但它不起作用。
有什么建议吗?