码迷,mamicode.com
首页 > 其他好文 > 详细

UIMenuController使用

时间:2016-05-07 08:58:39      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

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");
}


UIMenuController使用

标签:

原文地址:http://blog.csdn.net/gang544043963/article/details/51330393

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!