0

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

stockField1.stringValue = [sender representedObject];

(它是从菜单项处理程序设置的)。是否有必要向文本字段发送附加消息,或者我还能如何进行这项工作?

4

2 回答 2

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]];
}
于 2013-08-11T15:54:42.353 回答
0

这是迈克答案的 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)
于 2018-02-24T14:31:26.440 回答