5

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

4

1 回答 1

3

您在第一个方面走在了正确的轨道上,但-becomeFirstResponder实际上并没有让您的视图成为第一响应者——您必须要求-[NSWindow makeFirstResponder:]这样做。

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

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

于 2011-01-11T20:27:14.567 回答