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?
Michael luton
source share