突出显示NSTextField中的选择 [英] Highlight a selection in NSTextField
问题描述
我希望能够突出显示NSTextField中的一部分文本,但是我无法通过Google来做到这一点.
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.
我已经定义了NSRange,但是我找不到使用此范围突出显示文本的方法.我唯一出现的是textField.selectText,但据说这突出了整个字段.
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.
我正在使用Swift 2.
I'm using Swift 2.
推荐答案
您可能已经注意到,NSTextField
仅在具有焦点时才显示选择范围,即是第一响应者.在这种情况下,编辑由称为字段编辑器的NSTextView
处理.因此,请确保该字段具有焦点(例如,通过使用NSWindow
的makeFirstResponder:
方法),然后使用NSControl
方法currentEditor
获取字段编辑器,然后可以使用NSText
方法setSelectedRange:
.
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];
快速
let fieldEditor = textfield.currentEditor()
fieldEditor?.selectedRange = range
这篇关于突出显示NSTextField中的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!