为什么视图中的所有图层最初都设置为nil?

时间:2017-12-28 15:06:18

标签: swift cocoa

我通过在线跟踪代码来创建一个圆形的NSButton子类。但是,在我的子类中,layer始终为nil

我也发现了其他组件的类似行为,例如NSView,用于设置我需要将wantsLayer的{​​{1}}属性设置为NSView的图层的属性}。

在线示例代码

true

我的代码,

@IBInspectable
var shadowOpacity: Float {
    get {
        return layer.shadowOpacity
    }
    set {
        layer.shadowOpacity = newValue
    }
}

我的代码在控制台中打印@IBInspectable var shadowOpacity: Float { get { print(layer?) return layer.shadowOpacity } set { layer.shadowOpacity = newValue } }

默认情况下是否可以将nil设置为wantsLayer

1 个答案:

答案 0 :(得分:3)

您应该覆盖自定义类中NSButton的默认初始值设定项,并将wantsLayer设置为true

required init?(coder: NSCoder) {
    super.init(coder: coder)

    wantsLayer = true
}

override init(frame frameRect: NSRect) {
    super.init(frame: frameRect)

    wantsLayer = true
}