iOS10 + Gradient stop working [duplicate]

2019-09-12 05:56发布

This question already has an answer here:

Just been moved to Xcode8 and iOS10, providing support for iOS10 to one of the application.

Figure out weird issue, suddenly Gradient is not working.

I found that after applying Storyboard (Storyboard changes in Xcode8) changes gradient not visible to views.

Xcode 7.3 - Gradient Views -

enter image description here

Xcode 8 - Gradient Views -

enter image description here

Also, If I replace Storyboard with old storyboard it shows gradient, So there is something wrong with new Storyboard.

There is no change in code:

[view setOpaque:NO];
view.layer.cornerRadius = 45;
view.backgroundColor = [UIColor colorWithRed:23.0/255.0 green:29.0/255.0 blue:36.0/255.0 alpha:1.0];

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;

UIColor *color1 = [UIColor colorWithRed:33.0/255.0 green:39.0/255.0 blue:46.0/255.0 alpha:1.0];
UIColor *color2 = [UIColor colorWithRed:23.0/255.0 green:29.0/255.0 blue:36.0/255.0 alpha:1.0];
UIColor *color3 = [UIColor colorWithRed:14.0/255.0 green:20.0/255.0 blue:26.0/255.0 alpha:1.0];

NSArray *colorsArray = @[(id)color1.CGColor, (id)color2.CGColor, (id)color3.CGColor];

gradient.colors = colorsArray;
[gradient setLocations:@[@0.0, @0.35]];
[view.layer insertSublayer:gradient atIndex:0];

Let me know if any one figured it out.

Edit:

I didn't created new Storyboard, I just applied below changes as suggested by Xcode8

enter image description here

1条回答
时光不老,我们不散
2楼-- · 2019-09-12 06:26

The problem is that there has been a change in the timing of layout. Therefore your code is now running too soon. You are saying

gradient.frame = view.bounds

But at this moment, view has zero bounds. So gradient has zero frame! That is why you cannot see it. You are doing layout code in viewDidLoad. This was always wrong and now you see why.

Move your code to viewDidLayoutSubviews. At that time, view has its real bounds. You will have to use a condition so that your code only runs once.

查看更多
登录 后发表回答