4

实际上,我对 iOS7 中用于在 UITableView 上显示自定义上下文菜单的更改有点困惑。

我的代码如下:

- (void)viewDidLoad {
   UIMenuItem *deleteAction = [[UIMenuItem alloc]initWithTitle:NSLocalizedString(@"Delete", nil) action:@selector(delete:)];
   UIMenuItem *renameAction = [[UIMenuItem alloc]initWithTitle:NSLocalizedString(@"Rename", nil) action:@selector(rename:)];
   UIMenuController* mc = [UIMenuController sharedMenuController];
   mc.menuItems = [NSArray arrayWithObjects: renameAction, deleteAction, nil];
   [mc setTargetRect:CGRectMake(50.0, 50.0, 0, 0) inView:self.view];
   [mc setMenuVisible:YES animated:YES];
   [mc setMenuItems:@[deleteAction, renameAction]];
   [self becomeFirstResponder];

-(void)tableView:(UITableView*)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath*)indexPath withSender:(id)sender{
}

-(BOOL)tableView:(UITableView*)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath*)indexPath withSender:(id)sender {
if (tableView != nil && indexPath != nil)
{
    if (action == @selector(delete:)) {
            return YES;
        }
        if (action == @selector(rename:)) {
            return YES;
        }
    }
    return NO;
}

-(BOOL)tableView:(UITableView*)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath*)indexPath {
    return YES;
}

我的问题是,在 iOS 的预览版中一切正常。如果用户长按表格视图的单元格,则会出现自定义上下文菜单,但在 iOS7 中没有任何反应。方法被调用但没有显示。

4

1 回答 1

5

UIMenuController 有一个小问题,人们总是会错过。

要显示菜单,目标视图必须在响应者链中。许多 UIKit 视图默认不能成为响应者,因此您需要对它们进行子类化,以便为 canBecomeFirstResponder 返回 YES。

-(BOOL)canBecomeFirstResponder {
    return YES;
}

- (void)menuDelete:(id)sender {
    NSLog(@"delete");
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    NSLog(@"touchesBegan");

    [self becomeFirstResponder];
    UIMenuItem *menuItem = [[UIMenuItem alloc] initWithTitle:@"Delete" action:@selector(menuDelete:)];
    UIMenuController *menuCont = [UIMenuController sharedMenuController];
    [menuCont setTargetRect:self.frame inView:self.superview];
    menuCont.menuItems = [NSArray arrayWithObject:menuItem];
    [menuCont setMenuVisible:YES animated:YES];
}

我希望这有帮助。我很乐意帮助解决更多问题,所以如果我的建议仍然不能解决问题,请随时提供更新。

于 2013-12-14T22:14:35.960 回答