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

时间:2017-04-21 13:10:29

标签: objective-c cocoa cocoa-bindings nsbutton

我有几个NSButton(类型开/关),有一个动作集(oneButtonHasBeenPressed :),并且绑定到布尔值(self.isThisButtonActive1,self.isThisButtonActive2,self.isThisButtonActive3 ...)。

由于我有几个按钮,我的目标是通用,而不是在NSButton上声明几个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值?

1 个答案:

答案 0 :(得分:2)

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

div

如果设置了该值,则无需设置按钮的状态。

相关问题