Drawing gradient on UIView not working with iOS 9

2019-02-14 00:36发布

I'm trying to draw a gradient on the background view of a View Controller with iOS 9 but, I don't know why, isn't working

Here is my method, which is called from viewDidLoad

- (void)drawGradient
{
  CAGradientLayer *gradient = [CAGradientLayer layer];
  gradient.frame = self.view.bounds;

  gradient.colors = @[[UIColor greenColor], [UIColor redColor]];
  gradient.locations = @[@0.0, @1.0];

  [self.view.layer insertSublayer:gradient atIndex:0];
}

But nothing happens and gradient doesn't appear. What i'm doing wrong?

1条回答
可以哭但决不认输i
2楼-- · 2019-02-14 00:54

Thanks to Larme's comment, I figured out my mistake.

Instead of

gradient.colors = @[[UIColor greenColor], [UIColor redColor]];

the right this is

gradient.colors = @[(id)[UIColor greenColor].CGColor, (id)[UIColor redColor].CGColor];

Because gradient.colors expects a NSArray of CGColorRef. The (id) cast is also needed in order to create the NSArray.

查看更多
登录 后发表回答