UIView Background Gradient With Interface Builder View

I want to use a gradient as the background for a UIView. I know this is typically done with images and the backgroundColor property. However, I want to learn how to do this in code. Using https://stackoverflow.com/a/1931498/99683 I can create a UIView programmatically and give it a gradient layer. This works great.

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20, 340, 280, 100)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor redColor] CGColor], (id)[[UIColor yellowColor] CGColor], nil];
[view.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:view];

However, if I place a view in Interface Builder (with background set to clear) and try the same thing the gradient never shows up.

CAGradientLayer *gradient2 = [CAGradientLayer layer];
gradient2.frame = self.containerView.bounds;
gradient2.colors = [NSArray arrayWithObjects:(id)[[UIColor blueColor] CGColor], (id)[[UIColor greenColor] CGColor], nil];
[self.containerView.layer insertSublayer:gradient2 atIndex:0];

Is there something else I need to do in IB or code to make this work?


I faced the same problem, but finally figured out that the UIView hasn't been created at the point in the code where you're trying to set background gradient which I guess in your case might be one of the following -viewDidLoad or -viewWillAppear because of which

self.containerView.bounds will be {{0, 0}, {0, 0}}

Instead, you should set the gradient layer inside

viewDidAppear

at which point the views have been created.


This library supports to set a gradient background in Storyboard using by IB_DESIGNABLE / IBInspectable.

It's really useful.

https://github.com/recruit-mtl/EXTView/

链接地址: http://www.djcxy.com/p/69510.html

上一篇: 在文件中来回切换

下一篇: UIView背景渐变与界面生成器视图