CAGradientLayer不工作

SFF*_*SFF 9 objective-c calayer ios cagradientlayer

我创建了一个新项目.我挂QuartzCore.framework和进口<QuartzCore/QuartzCore.h>ViewController.m.

这是代码.

- (void)viewDidLoad {
    [super viewDidLoad];

    NSLog(@"view height %f", self.view.frame.size.height); // returns 667 on iPhone 6
    NSLog(@"view width %f", self.view.frame.size.width); // returns 375 on iPhone 6

    NSLog(@"layers count %lu", self.view.layer.sublayers.count); // returns 2

    // Gradient
    UIColor *colorOne = [UIColor blueColor];
    UIColor *colorTwo = [UIColor greenColor];
    NSArray *colorArray = @[colorOne, colorTwo];

    NSNumber *locationOne = [NSNumber numberWithFloat:0.0];
    NSNumber *locationTwo = [NSNumber numberWithFloat:1.0];
    NSArray *locationArray = @[locationOne, locationTwo];

    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = self.view.frame;
    gradientLayer.colors = colorArray;
    gradientLayer.locations = locationArray;

    [self.view.layer insertSublayer:gradientLayer atIndex:0];
    //[self.view.layer insertSublayer:gradientLayer above:[self.view.layer.sublayers firstObject]]; // didn't work either

    NSLog(@"layers count %lu", self.view.layer.sublayers.count); //returns 3
}
Run Code Online (Sandbox Code Playgroud)

我尝试将视图的背景颜色设置为clearColor,在其中调用它viewDidAppear,但它们都没有工作.我真的不知道自己错过了什么.在任何帮助下谢谢.

Ric*_*ley 40

你的颜色数组应该是NSArray *colorArray = @[(id)colorOne.CGColor, (id)colorTwo.CGColor];,因为colors数组需要CGColorRefs而不是UIColors,令人烦恼 - 请参阅CGGradientLayer文档

  • 烦人的部分不是需要CGColor,而是使用UIColor而不会在控制台中引起任何抱怨.我希望每次犯这个错误我都有镍 (10认同)