0

I am setting gradient to background of my view:

CAGradientLayer *grad = [CAGradientLayer layer];
grad.frame = self.contentView.frame;
grad.colors = @[(id)[[UIColor colorWithRed:1.0f green:0.5f blue:0.5f alpha:0.0f] CGColor],
                (id)[[UIColor colorWithWhite:1.0f alpha:0.5f] CGColor],
                (id)[[UIColor colorWithWhite:1.0f alpha:0.8f] CGColor],
                (id)[[UIColor colorWithWhite:0.0f alpha:1.0f] CGColor]];
grad.locations = @[@0.00f, @0.5f, @0.7f, @1.00f];        
self.layer.mask = grad;

Problem is, that every element (UIButton, UILabel...) on top of my view has that then same gradietn as parent. How can I set gradient only for view and not for items, that are on this view ?

Martin Perry
  • 9,232
  • 8
  • 46
  • 114

2 Answers2

1

Instead of setting the mask, you can set the gradient as sublayer of your view as below:

 [self.view setBackgroundColor:[UIColor clearColor]]; 
 [self.view.layer insertSublayer:grad atIndex:0];
kushyar
  • 1,191
  • 1
  • 6
  • 10
  • That didnt do the transparent background for me. I can see gradietn, but UIView is not transparent, so I cant see UIView under it. I try to set backgroundColor to ClearColor, but no effect. – Martin Perry Jun 08 '14 at 10:49
  • @MartinPerry it is hard to tell without seeing your code and view structure. but see if this helps: [self.view setBackgroundColor:[UIColor clearColor]]; – kushyar Jun 08 '14 at 10:51
  • Thanks.. it did it. I set clearColor in my storyboard and not in code. Setting it in code worked. – Martin Perry Jun 08 '14 at 10:53
  • @MartinPerry glad it worked. I will edit the answer to clarify. – kushyar Jun 08 '14 at 10:54
0

That is what a mask is supposed to do. :-)

You can work with a dedicated background view that is not superview (but probably sibling) to the other views that are drawn on top of it. When you don't use it as superview of subviews but as sibling to siblings (all share the same superview) then the sequence is of importance. Make sure that the background view is drawn first. That is in IB when it is located above of the "subviews" in the view hierarchy tree but within the same level.

Hermann Klecker
  • 14,039
  • 5
  • 48
  • 71