我正在使用以下方法在UITableViewCell中长按显示菜单。
我需要将按Delete菜单项的值传递给-(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 <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);
}
希望对您有所帮助。
干杯。