0

我有一个带有UITabBar. 每个选项卡都是一个,里面UINavigationController有几个UIViewControllers。其中一个视图控制器包含一个UITableView,我想显示一个用于删除长按的浮动菜单UITableViewCell

我正在使用UIMenuController但它没有显示,因为单元格拒绝成为第一响应者。

这是我的代码:

    - (void)viewDidLoad
    {
        [super viewDidLoad];

        UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
        lpgr.minimumPressDuration = 1.0; //second
        [table addGestureRecognizer:lpgr];

        [lpgr release];
    }

-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        CGPoint p = [gestureRecognizer locationInView: table];

        NSIndexPath *indexPath = [table indexPathForRowAtPoint:p];
        if (indexPath != nil) {
            UITableViewCell* cell = [self tableView:table cellForRowAtIndexPath: indexPath];

            [cell becomeFirstResponder];
            UIMenuItem *delete = [[UIMenuItem alloc] initWithTitle:@"Delete" action:@selector(delete:)];

            UIMenuController *menu = [UIMenuController sharedMenuController];
            [menu setMenuItems:[NSArray arrayWithObjects:delete, nil]];
            [menu setTargetRect:cell.frame inView:cell.superview];
            [menu setMenuVisible:YES animated:YES];
        }
    }
}

在 UITableViewCell 我已经覆盖了方法:

-(BOOL) canBecomeFirstResponder {
    return YES;
}

关于为什么细胞没有成为第一响应者的任何想法?

谢谢!

4

1 回答 1

1

我想我修复了你的代码:-)

-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        CGPoint p = [gestureRecognizer locationInView: self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
        if (indexPath != nil) {

            [self becomeFirstResponder];
            UIMenuItem *delete = [[UIMenuItem alloc] initWithTitle:@"Delete" action:@selector(customDelete:)];

            UIMenuController *menu = [UIMenuController sharedMenuController];
            [menu setMenuItems:[NSArray arrayWithObjects:delete, nil]];
            [menu setTargetRect:[self.tableView rectForRowAtIndexPath:indexPath] inView:self.tableView];
            [menu setMenuVisible:YES animated:YES];
        }
    }
}

- (void)customDelete:(id)sender {
//
}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(customDelete:) ){
        return YES;
    }
    return NO;
}

我做了以下..

  1. [自己成为FirstResponder];
  2. [菜单 setTargetRect:[self.tableView rectForRowAtIndexPath:indexPath] inView:self.tableView];
  3. 为 canPerformAction 添加了 true 如果您已实现该功能,则通常不需要

请将表格视图和其他内容更改为您的本地参考变量:-)

好读 - http://www.intridea.com/blog/2010/12/22/developers-notes-for-uimenucontroller

于 2012-12-03T09:46:26.800 回答