本文介绍了如何在不子类化NSButtonCell的情况下创建自定义主题的NSButton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在研究自定义主题NSButton.我发现的每个教程或指南都需要将NSButtonCell子类化,甚至 Apple的指南.

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

所有这些似乎都已过时,因为NSControl中的所有单元格方法都是优胜美地不推荐使用.我没有找到任何建议或指南来代替它.

All of those seem to be outdated, because all cell methods in NSControl are deprecated in Yosemite. I have not found any recommendations or guides what to use as a substitute.

这是我唯一能找到的陈述:

This is the only statement, I could find:

摘录自: OS X v10.10的AppKit发行说明

NSButton上没有单词.

NSTextField支持层支持的视图;因此,我在NSButton上尝试了相同的方法,但是没有效果.

NSTextField supports layer backed views; because of that, I tried the same approach on my NSButton, but that has no effect.

var btn = NSButton(NSMakeRect(0, 0, 50, 20))
btn.wantsLayer = true
btn.bordered = false
btn.layer?.backgroundColor = NSColor(calibratedWhite: 0.99, alpha: 1).CGColor
btn.layer?.borderWidth = 1
btn.layer?.borderColor = NSColor(calibratedWhite: 0.81, alpha: 1).CGColor

推荐答案

我肯定会花更多的时间研究layer-backed view方法.我不确定为什么它对您不起作用,因为没有理由说图层不能在NSButton(实际上是NSView派生类)上工作.

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.

从我正在处理的项目中提取了一些代码(自定义NSButton):

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

来自init()...

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()
}

如果您的自定义按钮需要某种形状,那么您甚至可以在下面使用CAShapeLayer来使您的背衬层成为特殊形状...更多细节需要研究.

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()
}

这篇关于如何在不子类化NSButtonCell的情况下创建自定义主题的NSButton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 09:58