How do I present a pull-down menu?

3.2k Views Asked by At

I'm looking to add a pull-down menu and I have no idea where to start. Apple's website guides me to UIMenu but I can't figure out how it works.

I know how to make a UIMenu:

NSMutableArray* actions = [[NSMutableArray alloc] init];

[actions addObject:[UIAction actionWithTitle:@"Edit"
                                       image:nil
                                  identifier:nil
                                     handler:^(__kindof UIAction* _Nonnull action) {
    
    // ...
}]];

UIMenu* menu =
[UIMenu menuWithTitle:@""
             children:actions];

How do I attach it to a UIButton?

2

There are 2 best solutions below

2
On BEST ANSWER

So it seems, after several radical rewrites of your question, that you want a menu that appears from a button. Well, a UIButton has a menu property and you assign a UIMenu to it. Done.

https://developer.apple.com/documentation/uikit/uibutton/3601189-menu?language=objc

If you also want the menu to appear as a response to a simple tap, rather than a long press, then also set the button's showsMenuAsPrimaryAction property to YES.

https://developer.apple.com/documentation/uikit/uicontrol/3601223-showsmenuasprimaryaction?language=objc

(A UIBarButtonItem has similar properties, in case you want to make the menu appear that way.)

0
On

Following up on matt's answer, here is some example code in Objective-C:

// Add a UIMenu (with three actions) to a UIButton
NSMutableArray  *theMenuActions = [[NSMutableArray alloc] initWithCapacity:3];

[theMenuActions addObject:[UIAction actionWithTitle:NSLocalizedString(@"FullName", @"")
                                              image:nil
                                         identifier:@"search_scope_full"
                                            handler:^(__kindof UIAction* _Nonnull action) {
self.mySearchScope  = @"full";
}]];
    
[theMenuActions addObject:[UIAction actionWithTitle:NSLocalizedString(@"FirstName", @"")
                                              image:nil
                                         identifier:@"search_scope_first"
                                            handler:^(__kindof UIAction* _Nonnull action) {
self.mySearchScope  = @"first";
}]];

[theMenuActions addObject:[UIAction actionWithTitle:NSLocalizedString(@"LastName", @"")
                                              image:nil
                                         identifier:@"search_scope_last"
                                            handler:^(__kindof UIAction* _Nonnull action) {
self.mySearchScope  = @"last";
}]];

// searchScopeBtn is a UIButton
self.searchScopeBtn.menu = [UIMenu menuWithTitle:NSLocalizedString(@"SearchScope", @"") 
                                        children:theMenuActions];
self.searchScopeBtn.showsMenuAsPrimaryAction = YES;

// When the UIButton is tapped, the UIMenu will appear