Adding a dynamic custom UIMenuItem to Copy & Paste Menu before it shows

六月ゝ 毕业季﹏ 提交于 2019-12-03 08:37:17

At startup somewhere:

UIMenuItem *testMenuItem = [[UIMenuItem alloc] initWithTitle:@"Test" action:@selector(test:)];
[UIMenuController sharedMenuController].menuItems = [NSArray arrayWithObject:testMenuItem];
[testMenuItem release];

And in your UITextView or UITextField subclass:

@implementation MyTextView
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(test:)) {
        // Return YES only if it's possible to perform the action at this time
        return YES;
    }
    return [super canPerformAction:action withSender:sender];
}
- (void)test:(id)sender {
    // Perform the action here
}
@end

If the question is still relevant then you could use the UIMenuControllerWillShowMenuNotification or the UIMenuControllerDidShowMenuNotification notification.
See the documentation here.

Code sample:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willShowMenu:) name:UIMenuControllerWillShowMenuNotification object:nil];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!