Display UIMenuController in editingDidBegin of a UITextField

拥有回忆 提交于 2019-12-03 10:08:05

I found a good solution to your question.

You can easily make the UIMenuController appear when you start editing your text field with this method:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    double delayInSeconds = 0.1;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        UIMenuController *menu = [UIMenuController sharedMenuController];
        [menu setTargetRect:textField.frame inView:textField.superview];
        [menu setMenuItems:[NSArray arrayWithObjects:
                            [[UIMenuItem alloc] initWithTitle:@"Test" action:@selector(test)],
                            nil]];
        [menu setMenuVisible:YES animated:YES];
    });
}

I use the dispatch_after call to make sure that the menu is show after all the defaults system calls on the UITextField are completed.

I also changed the inView:self.view part of the setTargetRect:: method with inView:textField.superview to be sure the menu is showing correctly in the container view of the text field.

If you also want to disable the default menu controls for a UITextField you can add this method to your controller:

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(cut:))
        return NO;
    else if (action == @selector(copy:))
        return NO;
    else if (action == @selector(paste:))
        return NO;
    else if (action == @selector(select:) || action == @selector(selectAll:))
        return NO;
    else
        return [super canPerformAction:action withSender:sender];
}

This work really well in the simulator. I hope this will help you!

A simpler solution:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [textField select:nil];
        UIMenuController *menuController = [UIMenuController sharedMenuController];
        [menuController setMenuVisible:YES animated:YES];
    }];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!