Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView Background Gradient With Interface Builder View

Tags:

ios

ios6

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?

like image 416
Michael Luton Avatar asked Feb 15 '13 23:02

Michael Luton


2 Answers

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.

like image 168
i_i_captain Avatar answered Nov 10 '22 01:11

i_i_captain


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/

like image 31
emeitch Avatar answered Nov 10 '22 00:11

emeitch