简体   繁体   English

如何为禁用的NSButton设置标题颜色?(OS X)

[英]How can I set title color for a disabled NSButton?(OS X)

I know that we can set a colored title for a button using attributed strings like this: 我知道我们可以使用如下属性字符串为按钮设置彩色标题:

let style = NSMutableParagraphStyle()
style.alignment = .Center
button.attributedTitle = NSAttributedString(string: "title",
             attributes: [ NSForegroundColorAttributeName : NSColor.redColor(),
                    NSParagraphStyleAttributeName : style])

In fact that's how I'm getting the red title to begin with, but it has no effect on the title color in the disabled mode (it is always gray); 实际上,这就是我开始使用红色标题的方式,但是在禁用模式下,它对标题颜色没有影响(始终为灰色)。 I guess in order to set that, I have to create an instance of the NSButton class and override some of its methods related to title color or override some of its properties to disable user interactions(when necessary) instead of disabling the button, but I don't know how. 我想为了进行设置,我必须创建NSButton类的实例,并覆盖其与标题颜色相关的某些方法,或者覆盖其某些属性以禁用用户交互(必要时),而不是禁用按钮,但是我不知道如何

There are some possible objective-C answers to this question here , here and here . 这里这里这里 ,都有一些可能的Objective-C答案。

Do you need it to be disabled by the definition of it not doing anything when touched? 您是否需要通过触摸时不执行任何操作的定义来禁用它?

If so, just have a flag in the button clicked function. 如果是这样,只需在按钮单击功能中添加一个标志。 So then, the button color could be red (example) when disabled but you can click it but nothing happens. 因此,禁用时按钮的颜色可能为红色(示例),但是您可以单击它,但是什么也没有发生。 Then if it it's green (example) then it'll allow it to do something. 然后,如果它是绿色(示例),则将允许它执行某些操作。

Your flag could be the color of the button checked through an if statement or set an actual variable. 您的标志可以是通过if语句检查的按钮的颜色,也可以是设置实际变量的颜色。

Create a NSButtonCell Subclass and assign it to the CELL (not the button) in IB. 创建一个NSButtonCell子类,并将其分配给IB中的CELL(而非按钮)。

Then implement 然后实施

func drawTitle(_ title: NSAttributedString, 
 withFrame frame: NSRect, 
        in controlView: NSView) -> NSRect

and return different attributedString for isEnabled or !isEnabled. 并为isEnabled或!isEnabled返回不同的attributedString。

You might also set the initial attributedTitle in 您也可以在中设置初始的attributedTitle

init (id)

EDIT: Only works if setWantsLayers is false 编辑:仅在setWantsLayers为false时有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM