How to update an NSTextField programatically and have value propagate through binding

Viewed 106

I have a case where I would like to programmatically assign the first responder to an NSTextField and then programmatically insert a value into the NSTextField as well.

I have this working with the following code:

field.window?.makeFirstResponder(field)
field.stringValue = "Auto generated value"

In the example above, field has a binding to my model. If the user chooses to edit Auto generated value and then hit the return key, the first responder is resigned and the edited value is set on my model. BUT, if the user chooses not to edit Auto generated value and hits the return key, the first responder is resigned but the model is not updated.

It's as if the field is not marked as dirty when programmatically updating the value.

I would like to avoid having to manually update the model when the case above occurs due to some complexities that I have left out in the example. I would like it to apply through whichever binding is set just like it would when the user manually types in the value.

Is this possible?

2 Answers

If you use binding with a NSTextField or any other AppKit control, you should perform programmatically value changes on the data source / model, instead of the other way around by manipulating the control value in code. By doing so, you will not have the problems as described in your question.

Inserting the text in the field editor starts an editing session (undocumented feature).

if window.makeFirstResponder(textField1),
    let fieldEditor = textField1.currentEditor() as? NSTextView {
    fieldEditor.insertText("Auto generated value", replacementRange: NSRange(location: 0, length: fieldEditor.textStorage?.length ?? 0))
}
Related