我想编辑一个NSView的边框宽度和背景颜色,并将这些值设置为IBInspectable
@IBInspectable var borderWidth: CGFloat{
set{
layer?.borderWidth = newValue
}
get{
return layer!.borderWidth
}
}
@IBInspectable var backgroundColor: NSColor{
set{
layer?.backgroundColor = newValue.CGColor
}
get{
return NSColor(CGColor: layer!.backgroundColor)!
}
}在init方法中,我写道:
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
wantsLayer = true
layer?.setNeedsDisplay()
}当我运行应用程序时,更改显示正确,但视图不会在界面构建器中实时呈现。我也没有收到任何错误或警告。
发布于 2015-06-16 21:58:17
我自己找到了解决方案:在接口构建器中呈现视图时,似乎不会调用init方法。作为解决方案,我必须添加一个全局变量,该变量在需要时创建一个CALayer():
@IBDesignable class CDPProgressIndicator: NSView {
// creates a CALayer() and sets it to the layer property of the view
var mainLayer: CALayer{
get{
if layer == nil{
layer = CALayer()
}
return layer!
}
}
//referencing to mainLayer ensures, that the CALayer is not nil
@IBInspectable var borderWidth: CGFloat{
set{
mainLayer.borderWidth = newValue
}
get{
return mainLayer.borderWidth
}
}
@IBInspectable var backgroundColor: NSColor{
set{
mainLayer.backgroundColor = newValue.CGColor
}
get{
return NSColor(CGColor: mainLayer.backgroundColor)!
}
}现在,它最终也在界面构建器中呈现。
发布于 2019-02-15 13:41:36
wantsLayer的设置足以在运行应用程序时创建图层,但它在IB中不起作用。您必须显式设置layer。我建议在prepareForInterfaceBuilder中这样做,这样您就可以在您的应用程序中使用经过批准的技术wantsLayer,但我们也会处理IB异常。例如:
@IBDesignable
class CustomView: NSView {
@IBInspectable var borderWidth: CGFloat {
didSet { layer!.borderWidth = borderWidth }
}
@IBInspectable var borderColor: NSColor {
didSet { layer!.borderColor = borderColor.cgColor }
}
@IBInspectable var backgroundColor: NSColor {
didSet { layer!.backgroundColor = backgroundColor.cgColor }
}
// needed because IB doesn't don't honor `wantsLayer`
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
layer = CALayer()
configure()
}
override init(frame: NSRect = .zero) {
super.init(frame: frame)
configure()
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
configure()
}
private func configure() {
wantsLayer = true
...
}
}这会处理这种IB边缘情况(bug?),但在运行应用程序时不会改变标准流程。
https://stackoverflow.com/questions/30864851
复制相似问题