1
votes

I have a NSTextField where I would like to enter text at the insertion point. I have a code that don't generate errors:

    let str = "Abc" 
    myTextField.insertText(str)

[edit] When, in the field there is 123|45 (the "|" represents the text insertion point), the output should be 123Abc|45.

Unfortunately don't work because it's deprecated. Here is the documentation. What is the replacement?

Please note that this question is for NSTextField not NSTextView, which has a question here: NSTextView's insertText method is deprecated in OS X v10.11. What is the replacement?

2
Why don't you read comments posted at stackoverflow.com/questions/32787814/… ?El Tomato
Hi El Tomato, actually I read the comment by bhaller: "With an NSTextField you would need to work with the field editor of the textfield, which is an NSTextView" But to be honest I don't understand it.Cue
@Cue , what is the the expected output do you need insertText when myTextField already has 44 ?Rajamohan S
Hi RAJAMOHAN-S, when the i-beam is between 4 and 4, the output should be 4Abc|4.Cue

2 Answers

2
votes

Get the field editor for the window that the text field is in, then use insertText(_:, replacementRange:) on that:

let textfield = NSTextField()...
if let fieldEditor = textfield.window?.fieldEditor(false, for: textfield) as? NSTextView {
    fieldEditor.insertText("abc", replacementRange: fieldEditor.selectedRange())
}

To clarify: this requires that the text field has input focus. If some other field has input focus the field editor will insert text there instead.

0
votes

If your textField has focus (is first responder) then any responder method like insertText: or inserText:replacementRange: will do the job. Problem is when you want to make the textField first responder (it will lose/reset the selectionRange).

func appendText(_ text: String, for textField: NSTextField) {
    makeFirstResponder(textField)
    if let fieldEditor = (textField.currentEditor() as? NSTextInputClient) {
        fieldEditor.insertText(text, replacementRange: fieldEditor.selectedRange())
    }
}

func makeFirstResponder(_ textField: NSTextField) {
    if textField.window?.firstResponder != textField.currentEditor() {
        textField.window?.makeFirstResponder(textField)
        if let length = textField.currentEditor()?.string.count {
            textField.currentEditor()?.selectedRange = NSMakeRange(length, 0)
        }
    }
}