Highlight a selection in NSTextField

扶醉桌前 提交于 2020-01-02 16:16:05

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/32376649/highlight-a-selection-in-nstextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!