如何在Swift中为NSTextView设置第一响应者? [英] How to set first responder for NSTextView in Swift?

查看:229
本文介绍了如何在Swift中为NSTextView设置第一响应者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在macOS项目中

我有一个简单的ViewController,它在状态项菜单应用程序上显示为弹出窗口.

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

我使用NSTableView更改视图文本的文本,具体取决于单击的项目.我使用的代码与此类似:

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)

(我使用insertText来将更改记录在撤消管理器中)

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

然后我突出显示文本:

// 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.

实际上,我希望NSTextView成为第一响应者,因此我可以直接复制所选文本.

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

如果按键盘上的Tab键,我将使textView成为第一响应者(灰色选择变为标准的天蓝色).

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

推荐答案

正确答案

在AppKit中,您需要:

Corrected Answer

In AppKit, you need:

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

在这种情况下,不检查acceptsFirstResponder可能很安全,但也不会受到伤害.

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

您需要致电mainTextField.becomeFirstResponder().

这篇关于如何在Swift中为NSTextView设置第一响应者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆