我有一个带有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;
}
关于为何该部门没有成为第一响应者的任何想法?
谢谢!
最佳答案
我想我已经修复了您的代码:-)
-(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;
}
我做了以下。
[自己成为第一响应者];
[菜单setTargetRect:[self.tableView rectForRowAtIndexPath:indexPath] inView:self.tableView];
为canPerformAction添加true如果已实现该功能,则不需要
请将tableview和其他内容更改为您的本地参考变量:-)
好读-http://www.intridea.com/blog/2010/12/22/developers-notes-for-uimenucontroller