1
votes

I'm using the following code to display custom items in the UIMenuController when selecting text within a UIWebView.

//Custom UIMenuController actions for highlighting and commenting
    UIMenuItem *highlightItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"Highlight", nil) action:@selector(highlightAction:) image:[UIImage imageNamed:@"HighlightIcon"]];
    UIMenuItem *commentItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"Comment", nil) action:@selector(createCommentAction:) image:[UIImage imageNamed:@"CommentIcon"]];

    [UIMenuController sharedMenuController].menuItems = @[highlightItem, commentItem];
    [[UIMenuController sharedMenuController] update];

It works fine the first time and display only the two custom options I have, but after that whenever some text is selected it shows the native options first and the custom ones on the next page of items.

I'm wondering how to permanently remove the native options - all other questions and examples don't seem to work for iOS 7+.

I also have this for enabling the menu:

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(highlightAction:) ||
        action == @selector(createCommentAction:) ||
        return YES;
    else if (action == @selector(copy:))
    {
        return NO;
    }

    return [super canPerformAction:action withSender:sender];
}

#pragma mark - privates
- (void)pressme:(id)sender
{
    [[UIMenuController sharedMenuController] setTargetRect:[sender frame] inView:self.view];
    [[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
    [[UIMenuController sharedMenuController] update];
}
1

1 Answers

0
votes

To disable default items, in method canPerformAction:withSender: instead of call super canPerformAction, just return NO.

Here is simple example how it should be for one action (just tried it, and it works):

// Let say we have textField property outlet

// Action to display menu
- (IBAction)showMenu:(id)sender {
    UIMenuItem *item = [[UIMenuItem alloc] initWithTitle:@"test" action:@selector(test:)];
    [UIMenuController sharedMenuController].menuItems = @[item];
    [[UIMenuController sharedMenuController] update];

    [self.textField becomeFirstResponder];
    UIMenuController *theMenu = [UIMenuController sharedMenuController];
    [theMenu setTargetRect:self.textField.frame inView:self.textField.superview];
    [theMenu setMenuVisible:YES animated:YES];
    [[UIMenuController sharedMenuController] update];

}

// Enable only "test:" selector here, disable others
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(test:))
        return YES;
    return NO;
}

enter image description here