在以编程方式设置其字符串值时,使NSTextField更新其绑定值

时间:2013-08-11 15:46:55

标签: cocoa cocoa-bindings nstextfield

我有一个NSTextField绑定到用户默认值中的键。当我按Enter或离开字段时,绑定值被正确更新(我有一个观察者)。但是,当我以编程方式设置文本字段的值时,绑定值不会更新。但是,文本字段显示了我设置的新字符串:

stockField1.stringValue = [sender representedObject];

(它是从菜单项处理程序设置的)。是否有必要向文本字段发送其他消息或我还能如何使其工作?

2 个答案:

答案 0 :(得分:1)

手动触发键值绑定如下:

- (void)symbolSelected: (id)sender
{
    NSTextField *field;
    switch ([sender tag]) {
        case 0:
            field = stockField1;
            break;
        case 1:
            field = stockField2;
            break;
        case 2:
            field = stockField3;
            break;
    }

    field.stringValue = [sender representedObject];
    NSDictionary *bindingInfo = [field infoForBinding: NSValueBinding];
    [[bindingInfo valueForKey: NSObservedObjectKey] setValue: field.stringValue
                                                  forKeyPath: [bindingInfo valueForKey: NSObservedKeyPathKey]];
}

答案 1 :(得分:0)

以下是Mike的答案的Swift版本,供参考:

guard
    let bindingInfo = self.infoForBinding(NSBindingName.value),
    let observedObject = bindingInfo[NSBindingInfoKey.observedObject] as? NSObject,
    let observedKeyPath = bindingInfo[NSBindingInfoKey.observedKeyPath] as? String else {
        return
}

observedObject.setValue(self.stringValue, forKeyPath: observedKeyPath)