我有一个定制的UIControl,我希望它有一个阴影,所以我设置相关属性在它的图层.在视图周围出现阴影,但阴影也会出现在UILabel的文本下,该文本是子视图.你如何阻止这个?我只想要外部超级视野的影子.
... 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 ... }
解决方法
当父视图的alpha值小于1.0或没有背景颜色(即设置为清除颜色)时,会发生这种情况.在这种情况下,阴影转换为子视图.有关详细信息,请参阅我的答案
here.
苹果Docs证明了这一点:
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.