Friday, 24 June 2016

UIMenuController

The singleton UIMenuController instance presents the menu interface. This menu is referred to as the editing menu. It is an easy way to add copy/paste menu options with in an app. You can also use it to expose custom features like saving, viewing, or deleting content.

Code for display UIMenuController:

First add a button and on click on that UIMenuController's will appear with menu options.

Here Button Action

#pragma mark -
-(IBAction) buttonAction:(UIButton *)sender{
    [self becomeFirstResponder];
    UIMenuItem *textMenu = [[UIMenuItem alloc] initWithTitle:@"Text" action:@selector(textButtonAction:)];
    UIMenuItem *copyMenu = [[UIMenuItem alloc] initWithTitle:@"Copy" action:@selector(copyButtonAction:)];
    UIMenuItem *editMenu = [[UIMenuItem alloc] initWithTitle:@"Edit" action:@selector(editButtonAction:)];
    UIMenuController *menuController = [UIMenuController sharedMenuController];
    [menuController setTargetRect:CGRectMake(sender.center.x, sender.frame.origin.y, 100, 60) inView:self.view];
    menuController.arrowDirection = UIMenuControllerArrowDown;
    menuController.menuItems = @[textMenu,copyMenu,editMenu];
    [menuController setMenuVisible:YES animated:YES];
}

#pragma mark -
-(void) textButtonAction:(id)sender{
    NSLog(@"Add text action code");
}
-(void) copyButtonAction:(id) sender{
    NSLog(@"Add copy action code");
}
-(void) editButtonAction:(id) sender{
    NSLog(@"Add edit action code");
}

Now we have to do one more thing
Override method canBecomeFirstResponder because default implementation return NO.

- (BOOL)canBecomeFirstResponder { return YES; }

Now we have enough code for display a UIMenuController with all added menu options.

No comments:

Post a Comment