简体   繁体   English

如何在Swift中为NSTextView设置第一响应者?

[英]How to set first responder for NSTextView in Swift?

Edit: in a macOS project 编辑:在macOS项目中

I have a simple ViewController which I display as popover on a status item menu app. 我有一个简单的ViewController,它在状态项菜单应用程序上显示为弹出框。

I change the text of the view text with a NSTableView, depending of which item is clicked. 我使用NSTableView更改视图文本的文本,具体取决于单击的项目。 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) (我使用insertText的目的是将更改记录在撤消管理器中)

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. 实际上,我希望NSTextView成为第一响应者,因此我可以直接复制所选文本。

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). 编辑:如果我按键盘上的Tab键,我将使textView成为第一响应者(灰色选择变为标准的天蓝色)。

Corrected Answer 正确答案

In AppKit, you need: 在AppKit中,您需要:

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

In this case, it's probably safe to not check acceptsFirstResponder , but it doesn't hurt either. 在这种情况下,不检查acceptsFirstResponder可能是安全的,但也不会造成伤害。

Original Answer ( UIKit ) 原始答案( UIKit

You need to call mainTextField.becomeFirstResponder() . 您需要调用mainTextField.becomeFirstResponder()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM