【问题标题】:Allow mixed state but not on click with NSButton (checkbox)允许混合状态,但不允许单击 NSButton(复选框)
【发布时间】:2018-04-05 09:17:04
【问题描述】:
我有一个以编程方式设置的复选框 (NSButton)。此复选框将设置为其他 on、off 或 mixed,但当用户单击它时,我希望它仅在 on 和 off 之间循环。
目前,当button.allowsMixedState = true 用户点击复选框时,它将在所有三种状态之间循环。
有没有办法让button.allowsMixedState = true 在被点击时只有on 和off 之间的复选框循环?
【问题讨论】:
标签:
swift
macos
checkbox
subclass
nsbutton
【解决方案1】:
通过继承 NSButtonCell 而不是 NSButton 并覆盖它的 nextState 属性,我终于能够让这个工作:
(此示例使用 Swift 4 运行)
// 0 is .off, 1 is .on and -1 is .mixed.
// We override nextState so that it can never be -1.
class MyButtonCell: NSButtonCell {
override var nextState: Int {
get {
return self.state == .on ? 0 : 1
}
}
}
这意味着我可以将复选框的状态设置为mixed,但是当用户单击它时,复选框只会在on 或off 之间循环。