Search code examples
objective-cmacoscocoainterface-builderspotlight

How to get the Spotlight-like text input effect in menu bar?


I want to have an icon in the menubar in my Mac app - and the icon should spawn a menu upon clicking. While having more entries in the menu, I would like to have a top row as a universal text entry field - like it is in Spotlight.

Is it possible to add such a field to NSMenu? Or should I do it as a panel-type window?


Solution

  • If you're using xcode 4 , make a custom view in interface builder and add a textfield or anything you want to it. In IB also drag and drop a "Menu" from the objects library with as many items as you want in it. Then simply ctrl+click the menu item you want to make into the text field (In your case it would be the top one) and drag to the custom view and select "view". Now when you open the menu, instead of showing a menu item in that space, it shows whatever was in your custom view.

    EDIT: As for your comment here's what you should do. Make your menu an outlet by opening the assistant editor view and ctrl+click from your menu to the header file that you want to use. now, simply make a method that will run whenever the menu will open, conveniently apple already made this, it's called menuWillOpen.

    - (void)menuWillOpen: nameOfYourMenu{
    
    [self performSelector:@selector(methodExecutedWhenMenuIsClicked) withObject:nil afterDelay:0.0 inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
    

    the delay at 0 will make it happen immediately, it must be done in the common modes run loop so that the menu will be updated even while it's open. Now just make the methodExecutedWhenMenuIsClicked and set it so the text field responds.

    - (void)methodExecutedWhenMenuIsClicked{
    
    [[yourTextfiled window] makeFirstResponder:yourTextField];