How to programmatically insert text into an NSTextField at the current cursor position

Let’s write this in the form of a utility function so it can be reused.

We’ll start by creating an insertTextAtCursor function with textField and newText parameters.

func insertTextAtCursor(textField: NSTextField, newText: String) {
    // ...
}

Next we’ll use the currentEditor() method to ensure that the text field we want to modify is the first responder (i.e. is focused).

func insertTextAtCursor(textField: NSTextField, newText: String) {
    if let currentEditor = textField.currentEditor() {
        // ...
    }
}

Now that we know the text field is indeed the first responder, we can safely insert the passed newText. Here’s the final function:

func insertTextAtCursor(textField: NSTextField, newText: String) {
    if let currentEditor = textField.currentEditor() {
        currentEditor.insertText(newText)
    }
}
Thanks for reading! If you liked this post, you may like others archived in: Swift, Cocoa. You can keep up to date with new posts by subscribing to the RSS Feed or by following me on Micro.blog.