0

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!

  • NSSearchField inherits from NSTextField. You can check this post how to select all of the text in a textfield https://stackoverflow.com/questions/26126273/select-all-text-in-a-nstextfield-using-swift – AmirZ Aug 06 '20 at 14:38
  • @AmirZ I cannot seem to work with an NSSearchField like I can a TextField. Can you please give an example of telling the SearchField to select all text? I tried variations of the examples in your link and could not get the right result. – Dart Fox Aug 06 '20 at 18:22
  • Have you tried running the code in the given link in a clean environment or playground? specially the selectText(_:) function which is the one that actually does the selecting and ends editing, as described in the docs: https://developer.apple.com/documentation/appkit/nstextfield/1399430-selecttext?language=swift – AmirZ Aug 06 '20 at 19:19
  • P.S the answer you are looking for is the one that is marked as correct answer, and you can simply replace the NSTextField With NSSearchField, the result will be the same. – AmirZ Aug 06 '20 at 19:22
  • Is the search field focused? – Willeke Aug 06 '20 at 20:49

1 Answers1

0

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
Tritonal
  • 607
  • 4
  • 16