Make NSTextField update its bound value when setting its string value programmatically

喜欢而已 提交于 2019-12-25 04:11:34

问题


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?


回答1:


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]];
}



回答2:


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)


来源:https://stackoverflow.com/questions/18173687/make-nstextfield-update-its-bound-value-when-setting-its-string-value-programmat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!