Macos IBInspectable未呈现NSView的层
我想编辑Macos IBInspectable未呈现NSView的层,macos,swift,interface-builder,Macos,Swift,Interface Builder,我想编辑NSView的边框宽度和背景色,并使这些值I可检测: @IBInspectable var borderWidth: CGFloat{ set{ layer?.borderWidth = newValue } get{ return layer!.borderWidth } } @IBInspectable var backgroundColor: NSColor{ set{ layer?.back
NSView
的边框宽度和背景色,并使这些值I可检测
:
@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()
}
当我运行应用程序时,更改会正确显示,但视图不会在界面生成器中实时渲染。我也没有收到任何错误或警告。我自己找到了解决方案:在界面生成器中呈现视图时,似乎没有调用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)!
}
}
现在,它最终也在界面生成器中呈现。wantsLayer的设置足以在运行应用程序时创建层,但在IB中不起作用。您必须明确设置
层。我建议您在prepareforprinterfacebuilder
中执行此操作,这样您就可以在应用程序中使用经批准的技术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边缘情况(错误?),但在运行应用程序时不会改变标准流程。您是否也在类定义中添加了@IBDesignable。是的:@Designable class cdpprogressicator:NSView
仅需B R I L A N t。谢谢