How to set first responder for NSTextView in Swift?

大憨熊 提交于 2019-12-10 23:52:48

问题


Edit: in a macOS project

I have a simple ViewController which I display as popover on a status item menu app.

I change the text of the view text with a NSTableView, depending of which item is clicked. The code I use is similar to this one:

mainTextField.insertText(newStr, replacementRange: theRange)

(I use insertText for the purpose to have the change recorded in undo manager)

Then I highlight the text:

// create the new NSRange
let range = NSRange(location: startRange, length: newStrLength)

// select the range in field
mainTextField.selectedRange = range

All work fine, except that the text is highlighted but with a light grey instead of the usual sky blue, indicating that the control is not the first responder. And when I click on the field the selection disappear.

Actually I would like that the NSTextView becomes first responder so I can directly copy the selected text.

Edit: if I press Tab key on the keyboard I got the textView to become first responder (and the grey selection becomes standard sky blue).


回答1:


Corrected Answer

In AppKit, you need:

if mainTextField.acceptsFirstResponder {
    mainTextField.window?.makeFirstResponder(mainTextField)
}

In this case, it's probably safe to not check acceptsFirstResponder, but it doesn't hurt either.

Original Answer (UIKit)

You need to call mainTextField.becomeFirstResponder().



来源:https://stackoverflow.com/questions/42727846/how-to-set-first-responder-for-nstextview-in-swift

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