Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight a selection in NSTextField

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.

like image 498
iphaaw Avatar asked Feb 09 '23 03:02

iphaaw


1 Answers

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
like image 73
JWWalker Avatar answered Feb 16 '23 03:02

JWWalker