Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop CALayer shadow from affecting subviews?

I have a custom UIControl, and I want it to have a shadow, so I set the relevant properties on its layer. A shadow appears around the view as desired, but a shadow also appears under the text of a UILabel, which is a subview. How do you stop this? I only want the shadow around the outer superview.

enter image description here

... init() {             label = UILabel()     label.translatesAutoresizingMaskIntoConstraints = false     self.translatesAutoresizingMaskIntoConstraints = false     addSubview(label)      self.layer.masksToBounds = false     self.layer.shadowColor = UIColor.blackColor().CGColor     self.layer.shadowOpacity = 1.0     self.layer.shadowRadius = 2.0      // Adding these lines trying to explicitly stop shadow on label...     label.layer.shadowOpacity = 0     label.layer.shadowColor = nil     ... } 
like image 826
Rob N Avatar asked Jul 01 '15 19:07

Rob N


1 Answers

This happens when parent view has alpha less than 1.0 or has no background color (i.e is set to clear color). In that case shadow translates to subviews. See my answer here for more details.

Apple Docs prove this:

Figure A-7 shows several different versions of the same sample layer with a red shadow applied. The left and middle versions include a background color so the shadow appears only around the border of the layer. However, the version on the right does not include a background color. In this case, the shadow is applied to the layer’s content, border, and sublayers.

Shadow

like image 157
NKorotkov Avatar answered Sep 25 '22 23:09

NKorotkov