标签:
iOS的APP中经常有这样的需求,长按某个地方(最多的是tableview的cell,例如聊天界面的某条消息),弹出一个黑色的横向菜单,如图:
这个控件就是系统自带的UIMenuController。
1. 使用这个控件需要做到以下三点:
a.在view(cell)或者viewController中调用-becomeFirstResponder方法;
b.你的view获得或者view controller需要实现 -canBecomeFirstResponder 方法,返回YES;
c.你的view获得或者view controller需要实现-canPerformAction:action withSender:sender 方法来隐藏或者现实响应的item;
2.代码展示
添加长按事件
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; longPress.numberOfTouchesRequired = 1; longPress.minimumPressDuration = 1.f; [self.msgContentView addGestureRecognizer:longPress];
- (void)handleLongPress:(UILongPressGestureRecognizer *)longPress { if (longPress.state != UIGestureRecognizerStateBegan){ return; }else{ NSLog(@"handleLongPress"); [self becomeFirstResponder]; UIMenuController *popupMenuController = [UIMenuController sharedMenuController]; NSMutableArray *array = [NSMutableArray arrayWithCapacity:0]; UIMenuItem *copyMenuItem = [[UIMenuItem alloc] initWithTitle:@"copy" action:@selector(messageCopy:)]; UIMenuItem *forwardMenuItem = [[UIMenuItem alloc] initWithTitle:@"forward" action:@selector(messageForward:)]; [array addObject:copyMenuItem]; [array addObject:forwardMenuItem]; [popupMenuController setMenuItems:array]; CGPoint location = [longPress locationInView:self]; [popupMenuController setTargetRect:CGRectMake(location.x, [longPress view].frame.origin.y, 0, 0) inView:self]; [popupMenuController setMenuVisible:YES animated:YES]; } }实现两个系统方法
//为了UIMenuController生效,以下两个系统方法必须实现 -(BOOL)canPerformAction:(SEL)action withSender:(id)sender{ if (action == @selector(messageCopy:)||action == @selector(messageForward:)) { return YES; } return NO; } - (BOOL)canBecomeFirstResponder{ return YES; }
- (void)messageCopy:(id)sender { NSLog(@"messageCopy"); } - (void)messageForward:(id)sender { NSLog(@"messageForward"); }
标签:
原文地址:http://blog.csdn.net/gang544043963/article/details/51330393