首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IBInspectable不是NSView的渲染层

IBInspectable不是NSView的渲染层
EN

Stack Overflow用户
提问于 2015-06-16 18:21:34
回答 2查看 641关注 0票数 3

我想编辑一个NSView的边框宽度和背景颜色,并将这些值设置为IBInspectable

代码语言:javascript
复制
@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方法中,我写道:

代码语言:javascript
复制
override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)

    wantsLayer = true
    layer?.setNeedsDisplay()
}

当我运行应用程序时,更改显示正确,但视图不会在界面构建器中实时呈现。我也没有收到任何错误或警告。

EN

回答 2

Stack Overflow用户

发布于 2015-06-16 21:58:17

我自己找到了解决方案:在接口构建器中呈现视图时,似乎不会调用init方法。作为解决方案,我必须添加一个全局变量,该变量在需要时创建一个CALayer()

代码语言:javascript
复制
@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)!
    }

}

现在,它最终也在界面构建器中呈现。

票数 3
EN

Stack Overflow用户

发布于 2019-02-15 13:41:36

wantsLayer的设置足以在运行应用程序时创建图层,但它在IB中不起作用。您必须显式设置layer。我建议在prepareForInterfaceBuilder中这样做,这样您就可以在您的应用程序中使用经过批准的技术wantsLayer,但我们也会处理IB异常。例如:

代码语言:javascript
复制
@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?),但在运行应用程序时不会改变标准流程。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30864851

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档