绑定选定的radiobox以启用Cocoa中的复选框

时间:2012-02-19 14:09:27

标签: xcode cocoa binding interface-builder cocoa-bindings

我之前没有使用过Cocoa绑定,所以我需要一些帮助。

我有一个带有三个按钮和一个复选框的单选按钮组(NSMatrix)。 我希望只有在选择了最后一个单选按钮时才启用该复选框。

在线找到一个教程,建议将单选按钮组的选定标签属性绑定到复选框的enabled属性。最后一个radiobutton需要标记为1,其他标记需要标记为0。 这非常有效。

问题是,如果选中复选框并且更改了单选按钮选项,则会保持选中状态,尽管它未启用。我希望当它变为禁用状态时,该框将被取消选中。

任何建议将不胜感激! 提前谢谢!

没有任何代码可以实现这一目标吗?

1 个答案:

答案 0 :(得分:1)

我怀疑没有代码就可以做到这一点。

我使用KVO在模型中处理这个问题。代码看起来像这样:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([@"checkWithInProcess" isEqualToString:keyPath]) {

        NSNumber *oldValue = [change objectForKey:NSKeyValueChangeOldKey];
        NSNumber *newValue = [change objectForKey:NSKeyValueChangeNewKey];

        BOOL oldValueAsBool = (oldValue != (id)[NSNull null]) && oldValue.boolValue;
        BOOL newValueAsBool = (newValue != (id)[NSNull null]) && newValue.boolValue;

        if (oldValueAsBool && !newValueAsBool) {
            // Save the value
            savedRecordValueWithInProcess = self.recordValueWithInProcess;
            self.recordValueWithInProcess = nil;
        } else if (!oldValueAsBool && newValueAsBool) {
            // Restore the value or set it to the default
            if (savedRecordValueWithInProcess)
                self.recordValueWithInProcess = savedRecordValueWithInProcess;
            else
                self.recordValueWithInProcess = [NSNumber numberWithBool:NO];
            savedRecordValueWithInProcess = nil;
        }
    }
}

在初始化期间:

[self addObserver:self
       forKeyPath:@"checkWithInProcess"
          options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
          context:[Characteristic class]];
相关问题