我正在使用以下方法在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;
}
答案 0 :(得分:4)
如此简单,只需创建一个类型为UIMenuItem
的类,在其中添加属性,然后使用UIMenuItem class
代替实际的UIMenuItem
。看看如何。
创建一个名为MyMenuItem
type UIMenuItem
的课程。
<强> MyMenuItem.h
强>
#import <UIKit/UIKit.h>
@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);
}
我希望它有所帮助。
干杯。
答案 1 :(得分:0)
Swift 4中已接受答案的修改版本
MenuItemWithIndexPath.swift:
node --version
用法:
class MenuItemWithIndexPath: UIMenuItem {
var indexPath: IndexPath?
init(title: String, action: Selector, indexPath: IndexPath) {
super.init(title: title, action: action)
self.indexPath = indexPath
}
}
答案 2 :(得分:0)
我以这种方式解决了这类问题:
self.becomeFirstResponder()
let deleteMenuItem = UIMenuItem(title: ConstantString.title_delete, action: #selector(deleteItem(_:)))
let menuController = UIMenuController.shared
menuController.menuItems = [deleteMenuItem]
menuController.accessibilityHint = String(indexPath.row)
menuController.setMenuVisible(true, animated: true)
@objc func deleteItem(_ sender: UIMenuController) {
print("delete menu item tapped! index path? \(sender.accessibilityHint)")
}
我以前使用过swift4。希望它会有所帮助。