How to create a custom themed NSButton without subclassing NSButtonCell?

后端 未结 1 1774
北荒
北荒 2020-12-24 02:34

I am currently working on a custom themed NSButton. Every tutorial, or guide I have found requires to subclass NSButtonCell, even the guide from Ap

相关标签:
1条回答
  • 2020-12-24 03:34

    I would definitely spend more time looking into the layer-backed view approach. I'm not sure why it didn't work for you because there's no reason for layers not to work on an NSButton (effectively an NSView derivative).

    Also weighing on looking more into layers is your mentioning of animation.

    Some code extracted from a project I am working on (custom NSButton):

    From init()...

        self.wantsLayer = true
        self.layerContentsRedrawPolicy = NSViewLayerContentsRedrawPolicy.OnSetNeedsDisplay
    
        self.layer?.borderColor = NSColor.gridColor().CGColor
        self.layer?.borderWidth = 0.5
        self.layer?.backgroundColor = NSColor.whiteColor().CGColor
    

    You can then get fine-grained control in the display cycle specific to layers with:

    override var wantsUpdateLayer:Bool{
        return true
    }
    
    override func updateLayer() {
        // your code here
        super.updateLayer()
    }
    

    If your custom button needs a shape then you can even use a CAShapeLayer below to make your backing layer a special shape...more detail to be looked into.

    override func makeBackingLayer() -> CALayer {
        return CAShapeLayer()
    }
    
    0 讨论(0)
提交回复
热议问题