将焦点设置在 NSMenu 中的 NSTextField 上?

发布于 2024-10-11 15:22:04 字数 436 浏览 1 评论 0原文

我在 Mac 状态栏中有一个 NSMenu,里面有一堆 NSMenuItems 和一个自定义视图。在自定义视图中我有一个 NSTextField。我想在打开菜单时将焦点设置在 NSTextField 上,就像在 Spotlight 菜单中一样,以便用户可以立即键入。

我已经尝试了很多方法,包括:

    [myTextField becomeFirstResponder];

    [myTextField selectText: self];
    [[myTextField currentEditor] setSelectedRange:NSMakeRange([[myTextField stringValue] length], 0)];

没有一个有效。

谢谢 亚历克斯

I have an NSMenu in the Mac statusbar, inside it I have a load of NSMenuItems and a custom view. Inside the custom view I have an NSTextField. I want to set the focus on the NSTextField when the menu is opened as in the Spotlight menu so the user can type straight away.

I have tried quite a few methods including:

    [myTextField becomeFirstResponder];

and

    [myTextField selectText: self];
    [[myTextField currentEditor] setSelectedRange:NSMakeRange([[myTextField stringValue] length], 0)];

but none of them work.

Thanks
Alex

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

满意归宿 2024-10-18 15:22:04

您在第一个方面处于正确的轨道上,但是 -becomeFirstResponder 实际上并没有使您的视图成为第一响应者 - 您必须调用 -[NSWindow makeFirstResponder:]为此。

Google 建议 NSMenu 实际上有一个附加窗口。您必须非常小心地使用它,但对其调用 makeFirstResponder: 是安全的。

有关此内容以及如何利用它的更多信息,请访问:https://web.archive.org/web/20171113100008/http://www.cocoabuilder.com/archive/cocoa/195835 -set-focus-on-nsview-in-an-nsmenuitem.html

You were on the right track with the first one, but -becomeFirstResponder doesn't actually make your view the first responder--you have to call -[NSWindow makeFirstResponder:] for that.

Google suggests that NSMenus actually have an attached window. You have to use it very carefully, but it is safe to call makeFirstResponder: on it.

More information about this and how to take advantage of it here: https://web.archive.org/web/20171113100008/http://www.cocoabuilder.com/archive/cocoa/195835-set-focus-on-nsview-in-an-nsmenuitem.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文