嗨,我想在IPhone SDK3.x中创建自定义的气泡菜单,如剪切/复制/粘贴菜单.我知道它是UIMenuController,但它只提供标准的剪切/复制/过去菜单.任何人都知道如何制作类似这样的气泡菜单.任何示例和代码供参考?
1)您需要将自定义菜单项添加到共享UIMenuController:
UIMenuItem* miCustom1 = [[[UIMenuItem alloc] initWithTitle: @"Custom 1" action:@selector( onCustom1: )] autorelease]; UIMenuItem* miCustom2 = [[[UIMenuItem alloc] initWithTitle: @"Custom 2" action:@selector( onCustom2: )] autorelease]; UIMenuController* mc = [UIMenuController sharedMenuController]; mc.menuItems = [NSArray arrayWithObjects: miCustom1, miCustom2, nil];
2)您需要在响应器链中的某处实现处理程序方法,以便在显示菜单时作为第一响应者的视图:
- (void) onCustom1: (UIMenuController*) sender { } - (void) onCustom2: (UIMenuController*) sender { }
3)你可以选择实现canPerformAction:在响应器链中,当你显示菜单时,它将是第一响应者的视图:
- (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]; }
4)如果要显示菜单的视图不支持显示菜单,(例如UIWebView将在用户进行长按时显示菜单,但UILabel没有内置支持显示菜单),然后你需要自己呈现菜单.这通常通过将UILongPressGestureRecognizer附加到视图,然后在回调中显示菜单来完成:
UILongPressGestureRecognizer* gr = [[[UILongPressGestureRecognizer alloc] initWithTarget: self action: @selector( onShowMenu: ) ] autorelease]; [_myview addGestureRecognizer: gr]; - (void) onShowMenu: (UIGestureRecognizer*) sender { [sender.view becomeFirstResponder]; UIMenuController* mc = [UIMenuController sharedMenuController]; CGRect bounds = sender.view.bounds; [mc setTargetRect: sender.view.frame inView: sender.view.superview]; [mc setMenuVisible: YES animated: YES]; }
注意,必须有一个视图声明要显示菜单的firstResponder.
5)确保您正在显示菜单的视图为canBecomeFirstResponder返回YES/TRUE.例如,如果您尝试将UILabel设为第一响应者,则它将返回NO,因此您必须将其子类化.
6)就是这样.调用操作回调时,您可能需要resignFirstResponder - 但要执行此操作,您需要实现逻辑以发现firstResponder.