为 NSButton 更改 mouseDown 上的 contentTintColor

问题描述

我有一个自定义按钮,它继承了 NSButton。当按钮处于按下状态时,我想更改内容色调颜色。这就是我所拥有的:

open override func mouseDown(with event: NSEvent) {
    // update contentTintColor
    contentTintColor = contentTintColorpressed
    // call super to inherit the click action
    super.mouseDown(with: event)
    // for some reason mouseUp doesn't trigger if I call super,so I have to override and manually call mouseUp 
    self.mouseUp(with: event)
}

这样做的结果是内容色调颜色变为背景颜色,因此按钮内容不可见。为什么只有当我将光标拖到按钮外时 contentTintColor 才会更新? demo

解决方法

您可以通过编程方式进行更改:

@IBOutlet weak var button: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    // Change button text color when tapping is on hold.
    button.setTitleColor(UIColor.red,for: .highlighted)
}

如果你有自定义的 UIButton 类,像这样使用:

self.setTitleColor(UIColor.red,for: .highlighted)