I want to be able to highlight a portion of text in an NSTextField but I've not been able to Google a way of doing this.
I have defined an NSRange but I cannot find a way of using this range to highlight the text. The only thing I have turned up is textField.selectText but this supposedly highlights the whole field.
I'm using Swift 2.
You may have noticed that an NSTextField
only shows a selection range when it has focus, i.e., is the first responder. In this case, editing is handled by an NSTextView
called the field editor. So, make sure the field has focus (e.g., by using the makeFirstResponder:
method of NSWindow
), then use the NSControl
method currentEditor
to get the field editor, and then you can use the NSText
method setSelectedRange:
.
ObjC
NSText* fieldEditor = [myField currentEditor];
[fieldEditor setSelectedRange: mySelRange];
Swift
let fieldEditor = textfield.currentEditor()
fieldEditor?.selectedRange = range
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With