UIMenuController使用

定制菜单项

如果你想使用定制菜单项,下面代码比较隐晦,但非常灵活。你需要检测是否用户长按并显示菜单,而最简单的方法就是在表格单元格中使用 UILongPressGestureRecognizer

UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[cell addGestureRecognizer:recognizer];

 

为了让菜单显示,目标视图必须在 responder 链中,很多 UIKit 视图默认并无法成为一个 responder ,因此你需要之类这些视图重载 canBecomeFirstResponder 方法范围 YES

nid%3D1717%7Ctitle%3D%7Cdesc%3DA%20UIMenuController%20with%20custom%20menu%20items.%7Clink%3Dnone

在下面例子中,我们使用定制类 TSTableViewCell 并实现了长按选择器

- (void)longPress:(UILongPressGestureRecognizer *)recognizer { 

    if (recognizer.state == UIGestureRecognizerStateBegan) {

        TSTableViewCell *cell = (TSTableViewCell *)recognizer.view;

        [cell becomeFirstResponder];

        UIMenuItem *flag = [[UIMenuItem alloc] initWithTitle:@"Flag"action:@selector(flag:)];

        UIMenuItem *approve = [[UIMenuItem alloc] initWithTitle:@"Approve"action:@selector(approve:)];

        UIMenuItem *deny = [[UIMenuItem alloc] initWithTitle:@"Deny"action:@selector(deny:)];


        UIMenuController *menu = [UIMenuController sharedMenuController];

        [menu setMenuItems:[NSArray arrayWithObjects:flag, approve, deny, nil]];

        [menu setTargetRect:cell.frame inView:cell.superview];

        [menu setMenuVisible:YES animated:YES];
    }
}

- (void)flag:(id)sender {
    NSLog(@"Cell was flagged");
}

- (void)approve:(id)sender {
    NSLog(@"Cell was approved");
}

- (void)deny:(id)sender {
    NSLog(@"Cell was denied");
}

 There is only one small gotcha with UIMenuItem: if the specified action is not implemented by your view controller, that item will not appear in the menu.

posted @ 2016-03-22 16:22  木易的博客  阅读(231)  评论(0编辑  收藏  举报