33

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
    ...
}
Rob N
  • 15,024
  • 17
  • 92
  • 165

2 Answers2

105

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

Community
  • 1
  • 1
NKorotkov
  • 3,591
  • 1
  • 24
  • 38
  • 3
    Yup, that outer view had alpha < 1.0. – Rob N Jul 10 '15 at 10:40
  • what is the solution to prevent this happening? – KvnH Nov 19 '19 at 08:40
  • 1
    @KvnH it depends. If you don't need a (semi)transparent superlayer just correct it's alpha to 1. In case you actually do need a (semi)transparent layer "behind" your views/layers just create another parent layer/view and add your transparent subview/sublayer to it as well as all other views. It should work. – NKorotkov Dec 10 '19 at 13:13
  • Thanks ! you saved me a lot of time. I was clueless – talshahar May 23 '21 at 13:44
  • Thank you. wasted more than 5 hours of time banging my head. – CKT Jun 21 '22 at 09:33
2

its easy just change your subviews parent.

in other words make new parent above the your transparent shadow View and insert the subViews to this new parent view.

jamal zare
  • 1,037
  • 12
  • 13