Step 1: Creating Menu Items
UIMenuItem* miCustom1 = [[UIMenuItem alloc] initWithTitle:@"Custom 1" action:@selector(onCustom1:)]; UIMenuItem* miCustom2 = [[UIMenuItem alloc] initWithTitle: @"Custom 2" action:@selector(onCustom2:)];
Step 2: Create MenuController
UIMenuController* mc = [UIMenuController sharedMenuController];
Step 3: add items to the menu controller
mc.menuItems = [NSArray arrayWithObjects: miCustom1, miCustom2, nil];
Step 4. Creating action methods for items
- (void) onCustom1: (UIMenuController*) sender { } - (void) onCustom2: (UIMenuController*) sender { }
Step 5: its optional to install FirstResponder for actions
- (BOOL) canPerformAction:(SEL)action withSender:(id)sender { if ( action == @selector( onCustom1: ) ) { return YES; // logic here for context menu show/hide } if ( action == @selector( onCustom2: ) ) { return NO; // logic here for context menu show/hide } if ( action == @selector( copy: ) ) { // turn off copy: if you like: return NO; } return [super canPerformAction: action withSender: sender]; }
Step 6: Finally, show off your MenuController for some buttons.
UIMenuController* mc = [UIMenuController sharedMenuController]; CGRect bounds = sender.view.bounds; [mc setTargetRect: sender.view.frame inView:sender.view.superview]; [mc setMenuVisible:YES animated: YES];
source share