ios开发之实现长按UITableViewCell弹出UIMenuController

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/bl1988530/article/details/9195583

项目中需要这个功能,网上找了下资料,有的说得不是很清楚,走了很多弯路才实现了,下面是实现步骤:

1.给cell添加UILongPressGestureRecognizer和相应处理事件

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{    

   ..............

   UILongPressGestureRecognizer * longPressGesture =         [[UILongPressGestureRecognizer alloc]initWithTarget:selfaction:@selector(cellLongPress:)];

   [cell addGestureRecognizer:longPressGesture];

   return cell;

}

2.配置和显示UIMenuController

- (void)cellLongPress:(UIGestureRecognizer *)recognizer{   

    if (recognizer.state == UIGestureRecognizerStateBegan) {

        CGPoint location = [recognizer locationInView:self];

        NSIndexPath * indexPath = [self indexPathForRowAtPoint:location]; 

        UIMyTableViewCell *cell = (UIMyTableViewCell *)recognizer.view;

     //这里把cell做为第一响应(cell默认是无法成为responder,需要重写canBecomeFirstResponder方法)

        [cell becomeFirstResponder];

        

        UIMenuItem *itCopy = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(handleCopyCell:)];

        UIMenuItem *itDelete = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(handleDeleteCell:)];        

        UIMenuController *menu = [UIMenuController sharedMenuController];

[menu setMenuItems:[NSArray arrayWithObjects:itCopy, itDelete,  nil]];

        [menu setTargetRect:cell.frame inView:self];

        [menu setMenuVisible:YES animated:YES];

        

        [itCopy release];

        [itDelete release];

    }

}

- (void)handleCopyCell:(id)sender{//复制cell

    NSLog(@"handle copy cell");

}


- (void)handleDeleteCell:(id)sender{//删除cell

    NSLog(@"handle delete cell");

}



3.在自定义的cell里重写canBecomeFirstResponder方法,返回yes

//为了让菜单显示,目标视图必须在responder链中,很多UIKit视图默认并无法成为一个responder,因此你需要使这些视图重载 canBecomeFirstResponder方法,并返回YES

- (BOOL)canBecomeFirstResponder{

    return YES;

}


经过这几步,就可以成功显示了,又在网上看到一篇讲这个的外文,分享一下:

http://www.intridea.com/blog/2010/12/22/developers-notes-for-uimenucontroller


展开阅读全文

没有更多推荐了,返回首页