通过UIMenuController的UIMenuItem传递值

我正在使用以下方法在UITableViewCell中长按显示菜单。

我需要将删除菜单项的值传递给 – (void)numberDelete方法。

-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer { if(gestureRecognizer.state == UIGestureRecognizerStateBegan) { CGPoint p = [gestureRecognizer locationInView: self.pullTableView]; NSIndexPath *indexPath = [self.pullTableView indexPathForRowAtPoint:p]; if(indexPath != nil) { [self becomeFirstResponder]; NSInteger *row = indexPath.row; //need to pass this row value through @selector(numberDelete:) UIMenuItem *delete = [[UIMenuItem alloc] initWithTitle:@"Delete" action:@selector(numberDelete:)]; UIMenuController *menu = [UIMenuController sharedMenuController]; [menu setMenuItems:[NSArray arrayWithObjects:delete, nil]]; [menu setTargetRect:[self.pullTableView rectForRowAtIndexPath:indexPath] inView:self.pullTableView]; [menu setMenuVisible:YES animated:YES]; } } } -(void)numberDelete:(id)sender { //receive value of row here } -(BOOL)canBecomeFirstResponder { return YES; } -(BOOL)canPerformAction:(SEL)action withSender:(id)sender { if (action == @selector(customDelete:) ){ return YES; } return NO; } 

这么简单,只需创建一个UIMenuItem类,在其中添加属性,并使用您的UIMenuItem class而不是实际的UIMenuItem 。 怎么看。

创建一个类说MyMenuItem type UIMenuItem

MyMenuItem.h

 #import  @interface MyMenuItem : UIMenuItem @property(nonatomic, strong)NSIndexPath *indexPath; @end 

MyMenuItem.m

 #import "MyMenuItem.h" @implementation MyMenuItem @end 

接着

 { MyMenuItem *deleteMenuItem = [[MyMenuItem alloc] initWithTitle:@"Delete" action:@selector(numberDelete:)]; deleteMenuItem.indexPath=indexPath;//Assign to property UIMenuController *menu = [UIMenuController sharedMenuController]; [menu setMenuItems:[NSArray arrayWithObjects:deleteMenuItem, nil]]; [menu setTargetRect:[self.pullTableView rectForRowAtIndexPath:indexPath] inView:self.pullTableView]; [menu setMenuVisible:YES animated:YES]; } -(void)numberDelete:(id)sender { //receive value of row here. The sender in iOS 7 is an instance of UIMenuController. UIMenuController *targetSender = (UIMenuController *)sender ; MyMenuItem *menuItem=(MyMenuItem *)[targetSender.menuItems firstObject]; NSLog(@"%d",menuItem.indexPath.row); } 

我希望它有所帮助。

干杯。

Swift 4中接受的答案的修改版本

MenuItemWithIndexPath.swift:

 class MenuItemWithIndexPath: UIMenuItem { var indexPath: IndexPath? init(title: String, action: Selector, indexPath: IndexPath) { super.init(title: title, action: action) self.indexPath = indexPath } } 

用法:

 let menu = UIMenuController.shared menu.menuItems = [MenuItemWithIndexPath(title: "Delete", action: #selector(numberDelete(sender:)), indexPath: indexPath)] menu.setTargetRect(tableView.rectForRow(at: indexPath), in: tableView) menu.setMenuVisible(true, animated: true) @objc func numberDelete(sender:UIMenuController) { if let menuItem = sender.menuItems?.first as? MenuItemWithIndexPath, let indexPath = menuItem.indexPath { print("delete at indexPath: \(indexPath)") } }