NSSearchField - How to select all text? (Swift/Storyboards on macOS)

279 Views Asked by At

It seems everything online is mostly about iOS/UI controls, not macOS/Cocoa NS controls. Anyway, How does one make an NSSearchField select all text in the field programatically? I have tried multiple methods adapted from the iOS UISearchBar implementations, but none of them compiled or worked. I just want to, for instance, press a button and have it hilight the text that is inside the NSSearchField's text field. I can't seem to find a method within it that allows this to happen.

Thank you for your help/consideration!

1

There are 1 best solutions below

0
Tritonal On

All editing in NSTextField is handled by NSText (which inherits from NSTextView). So, to select the text in your search field, you need to set the selected range in field's current editor. This example highlights the whole text.

Objective-C:

NSRange range = NSMakeRange(0, searchField.stringValue.length);
NSText *editor = [searchField currentEditor];
[editor setSelectedRange:range];

Swift

let range = NSRange(location: 0, length: searchField.stringValue.length)
let editor = searchField.currentEditor()
editor?.selectedRange = range