0
我正在開發一個包含最新SDK的iOS應用程序。用CAGradientLayer替換CALayer不起作用
我想改變動態背景層:
#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;
}
但它不工作。
有什麼建議嗎?