NSSearchField results menu
Asked Answered
B

2

8

I've been searching for hours and still haven't found an answer to this. How can you get an NSSearchField to display a menu with results. I can use the recent searches menu to display results, but how do I make the menu display programmatically? Thanks for any help.

Balling answered 11/11, 2011 at 3:43 Comment(0)
A
8

I believe Apple does this with some private methods. Maybe it uses an NSWindow instead of an NSMenu. One way to do it is to implement this in your NSSearchField delegate assuming you have an IBOutlet pointing to the NSSearchField.

- (void)controlTextDidEndEditing: (NSNotification *)aNotification
{
    NSString *searchString = [searchField stringValue];

    NSMenu *menu = [[NSMenu alloc] initWithTitle: @"results"];

    [menu addItemWithTitle: searchString action: @selector(someAction:) keyEquivalent: @""];
    [menu addItemWithTitle: @"someString" action: @selector(someOtherAction:) keyEquivalent: @""];

    NSEvent *event =  [NSEvent otherEventWithType: NSApplicationDefined
                                         location: [searchField frame].origin
                                    modifierFlags: 0
                                        timestamp: 0
                                     windowNumber: [[searchField window] windowNumber]
                                          context: [[searchField window] graphicsContext]
                                          subtype: NSApplicationDefined
                                            data1: 0
                                            data2: 0];

    [NSMenu popUpContextMenu: [menu autorelease] withEvent: event forView: searchField];
}

Note that showing a menu prevents further typing in the NSSearchField. That's why I used controlTextDidEndEditing:and not controlTextDidChange:. You should also check NSEvent's Class Reference for more customization of the event.

Allocate answered 11/11, 2011 at 12:26 Comment(2)
Thanks, works perfectly. The only change was that I modified the location parameter in the event to shift the menu down by about 5 so that it doesn't overlap the search field. Thanks!Balling
I haven't tested this but maybe you could change the whole NSEvent thing to [NSEvent currentEvent]. Perhaps then it gets the default location etc.Allocate
O
1

Apple has some sample code similar to what you need. The sample code uses NSTextField (which is a parent class of NSSearchField). Hopefully, this solves your problem.

Otranto answered 11/2, 2015 at 7:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.