0

我正在使用最新的 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;
}

但它不起作用。

有什么建议吗?

4

1 回答 1

1

试试这个

- (void)changeBackgroundWithLayer:(CALayer*)newLayer
{
    [_gradientBackground removeFromSuperlayer], _gradientBackground = nil;
    [self.layer insertSublayer:newLayer atIndex:0];
    _gradientBackground = newLayer;
}

这将在每种情况下删除并将其_gradientBackground设置为nil,这在 Objective-C 中是完全可以接受的。将newLayer添加到图层层次结构并gradientBackground更新图层。

于 2013-03-22T15:14:59.320 回答