UIView background gradient with interface design

I want to use a gradient as a background for a UIView. I know that this is usually done with images and the backgroundColor property. However, I want to learn how to do this in code. Using https://stackoverflow.com/a/4129602/2322322, using qaru.site/questions/30002 / ... , I can programmatically create a UIView 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 placed the view in Interface Builder (with the background set for cleaning), and try the same thing, that the gradient will never appear.

 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 anything else I need to do in IB or code to make this work?

+7
source share
2 answers

I ran into the same problem, but finally realized that the UIView was not created at the point in the code where you are trying to set the background gradient, which I suppose in your case could 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

after which the views are created.

+3
source

This library supports setting a gradient background in a storyboard using IB_DESIGNABLE / IBInspectable.

This is really helpful.

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

+1
source

All Articles