阻止 CALayer 阴影影响子视图?

Stop CALayer shadow from affecting subviews?

我有一个自定义的UIControl,我想让它有一个影子,所以我在它的layer上设置了相关的属性。根据需要,视图周围会出现阴影,但是 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

Apple 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.

只需更改您的子视图父级即可。

换句话说,在透明阴影视图上方创建新的父视图,并将子视图插入到这个新的父视图中。