Make NSTextField update its bound value when setti

2019-09-09 05:22发布

I have an NSTextField bound to a key in the user defaults. When I press enter or leave the field the bound value is properly updated (I have an observer for it). However when I programmatically set the value of the text field the bound value is not updated. The text field however shows the new string I set with:

stockField1.stringValue = [sender representedObject];

(it's set from a menu item handler). Is it necessary to send an additional message to the text field or how else can I make this work?

2条回答
Summer. ? 凉城
2楼-- · 2019-09-09 05:59

Manually triggering key-value binding goes like this:

- (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]];
}
查看更多
手持菜刀,她持情操
3楼-- · 2019-09-09 06:02

Here's the Swift version of Mike's answer, for reference:

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)
查看更多
登录 后发表回答