将焦点设置在 NSMenu 中的 NSTextField 上?
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在第一个方面处于正确的轨道上,但是
-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
NSMenu
s actually have an attached window. You have to use it very carefully, but it is safe to callmakeFirstResponder:
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