Default textField in a status item
I have a text field inside a status item and would like for it to be immediately active when t开发者_运维技巧he status item is clicked. I tried the usual becomeFirstResponder
in applicationDidFinishLaunching
and then in awakeFromNib
, but it didn't work. I imagine t's because the status item's menu is not open when those methods get called at launch, possibly ignoring it. Then I tried to set an action when the status item was clicked, but someone here told me that those actions can only be executed if the status item doesn't have a dropdown menu, which mine does. What I want is for the status item to be clicked, and the dropdown menu to appear with the textfield activated so typing can begin immediately. I'm using a custom view to show the textfield in the menu, not sure if that's relevant but maybe something else is supposed to be used in this situation?
Thanks.
You could set an object as the delegate
of the status item's menu, implement the ‑menuWillOpen:
delegate method and then use ‑performSelector:withObject:afterDelay:modes:
to set the first responder.
This will ensure that the call to make the text field the first responder happens in the next run through the event loop, after the menu has opened. You need to pass in NSRunLoopCommonModes
or NSEventTrackingRunLoopMode
in the array of run loop modes passed to the modes:
parameter, because the normal performSelector:withObject:afterDelay:
method will not call the selector until the menu is closed.
- (void)menuWillOpen:(NSMenu *)menu
{
[self performSelector:@selector(highlightField) withObject:nil afterDelay:0.0 inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
}
- (void)highlightField
{
[[yourTextField window] makeFirstResponder:yourTextField];
}
精彩评论