以编程方式更改 NSButton 状态和绑定值

Change NSButton status and the binding value programmatically

我有几个 NSButton(类型 On/Off),带有一个操作集 (oneButtonHasBeenPressed:),并且值绑定到布尔值(self.isThisButtonActive1、self.isThisButtonActive2、self.isThisButtonActive3 ...)。

因为我有几个按钮,我的目标是通用的,而不是在 NSButtons 或几个动作上声明几个 IBOutlet 属性,只保留布尔值。

如果在按下按钮并因此关联布尔值后测试失败,我无法反转 NSButton 的状态。

- (IBAction)oneButtonHasBeenPressed:(id)sender {

    NSButton *button = (NSButton*)sender;
    // At this point, button state has already changed by IB

    if (testIsNotOk) {

       // Not ok as it goes in an infinite loop in oneButtonHasBeenPressed, but it propagates correctly KVO
       // [button performClick:nil];

       // This revert the state of my button correctly
       button.state = !button.state;

       // Now I need to change my boolean binded to this NSButton,
       // Idea is: self.isThisButtonActive = !self.isThisButtonActive
       // But I have several buttons and several booleans and can't easily link each buttons to the booleans while keeping generic (?)

       // [button didChangeValueForKey:@"value"];    // KO
       // [button didChangeValueForKey:@"state"];    // KO
    }
}

如何更改按钮的状态,然后传播绑定到 NSButton 值的布尔值的更改?

如果你不想使用插座,为每个按钮创建一个动作或使用按钮的标签,然后你可以从绑定中获取密钥。

NSDictionary *dictionary = [sender infoForBinding:NSValueBinding];
id object = [dictionary objectForKey:NSObservedObjectKey];
NSString *keyPath = [dictionary objectForKey:NSObservedKeyPathKey];
if (object && keyPath)
    [object setValue:@NO forKeyPath:keyPath];

如果设置值,则不必设置按钮的状态。