ios - 阻止 CALayer 阴影影响 subview ?

标签 ios uiview ios8 calayer shadow

我有一个自定义的UIControl,我想让它有一个阴影,所以我在它的layer上设置了相关的属性。阴影会根据需要出现在 View 周围,但阴影也会出现在作为 subview 的 UILabel 的文本下方。你怎么阻止这个?我只想要外部 super View 周围的阴影。

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

最佳答案

当父 View 的 alpha 小于 1.0 或没有背景颜色(即设置为透明颜色)时会发生这种情况。在这种情况下,阴影会转化为 subview 。看我的回答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.

Shadow

关于ios - 阻止 CALayer 阴影影响 subview ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31170177/

相关文章:

xcode - 如何快速清除 map View 上的图钉?

ios - 如何设置AppStore支持的最高iOS版本

ios - 显示带有操作的搜索栏(栏项)

ios - 使用自动布局嵌入单个 View 中的两个 UITableView 的动态高度

ios - 将类扩展继承子句迁移到协议(protocol)扩展

ios - 如何调试大的 UIView 内存分配

ios - UIView 的宽度和高度为零,即使它是可见的

ios - 如何识别向谁发送推送通知?

ios - iPad 浏览量 "frame"

ios - 获取 textView contentsize 高度在 iOS 8 中是错误的