1. 在 Controller 中使用
在 Controller 中使用 UIMenuController 较为简单,只需要满足一个条件:
- 重写
- (BOOL)canBecomeFirstResponder
方法,返回 YES
1.1 canBecomeFirstResponder
- (BOOL)canBecomeFirstResponder
{
return YES;
}
1.2 Sample
- (IBAction)buttonPressed:(UIButton *)sender
{
UIMenuController * menu = [UIMenuController sharedMenuController];
menu.menuItems = nil;
menu.menuItems = [self contextMenuItems];
[menu setTargetRect:sender.frame inView:self.view];
[menu setMenuVisible:YES animated:YES];
}
- (NSArray *)contextMenuItems
{
NSMutableArray * items = [NSMutableArray array];
{
UIMenuItem * item = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyContent:)];
[items addObject:item];
}
{
UIMenuItem * item = [[UIMenuItem alloc] initWithTitle:@"分享" action:@selector(shareContent:)];
[items addObject:item];
}
return items;
}
- (void)copyContent:(id)sender
{
NSLog(@"复制");
}
- (void)shareContent:(id)sender
{
NSLog(@"分享");
}
2. 在 View 中使用
在 View (Cell)中使用 UIMenuController 比较麻烦,需要满足以下三个条件:
- 重写
- (BOOL)canBecomeFirstResponder
方法,返回 YES - 在 View 中调用
[self becomeFirstResponder]
方法 - 重写
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
方法,根据 action 判断是否显示相应的 UIMenuItem(参考:- (BOOL)canPerformAction:(SEL)action withSender:(id)sender)
2.1 canPerformAction
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if(action == @selector(copyContent:))
{
return YES;
}
else if (action == @selector(shareContent:))
{
return YES;
}
return [super canPerformAction:action withSender:sender];
}
2.2 Sample
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
if (self)
{
// 监听长按事件,为了复制和分享
UILongPressGestureRecognizer * longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[self addGestureRecognizer:longPressRecognizer];
}
return self;
}
- (void)showMenu
{
[self becomeFirstResponder];
UIMenuController * menu = [UIMenuController sharedMenuController];
menu.menuItems = nil;
menu.menuItems = [self contextMenuItems];
[menu setTargetRect:self.bounds inView:self];
[menu setMenuVisible:YES animated:YES];
}
- (void)longPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
UIGestureRecognizerState state = gestureRecognizer.state;
if (state == UIGestureRecognizerStateBegan) // 长按开始即触发,获取良好用户体验
{
[self showMenu];
}
}
- (NSArray *)contextMenuItems
{
NSMutableArray * items = [NSMutableArray array];
{
UIMenuItem * item = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyContent:)];
[items addObject:item];
}
{
UIMenuItem * item = [[UIMenuItem alloc] initWithTitle:@"分享" action:@selector(shareContent:)];
[items addObject:item];
}
return items;
}
- (void)copyContent:(id)sender
{
NSLog(@"复制");
}
- (void)shareContent:(id)sender
{
NSLog(@"分享");
}