1) First, please do this in your view controller's viewDidLoad
method.
UIMenuItem *testMenuItem = [[UIMenuItem alloc] initWithTitle:@"Test"
action:@selector(test:)];
[[UIMenuController sharedMenuController] setMenuItems: @[testMenuItem]];
[[UIMenuController sharedMenuController] update];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuControllerWillShow:) name:UIMenuControllerWillShowMenuNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuControllerWillHide:) name:UIMenuControllerWillHideMenuNotification object:nil];
2) Then, add these two Methods. and set menuFrame inView
to your cell
-(void)menuControllerWillShow:(NSNotification *)notification{
//Remove Will Show Notification to prevent
// "menuControllerWillShow" function to be called multiple times
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIMenuControllerWillShowMenuNotification object:nil];
//Hide the Original Menu View
UIMenuController* menuController = [UIMenuController sharedMenuController];
CGSize size = menuController.menuFrame.size;
CGRect menuFrame;
menuFrame.origin.x = self.tableView.frame.origin.x;
menuFrame.size = size;
[menuController setMenuVisible:NO animated:NO];
//Modify its target rect and show it again to prevent glitchy appearance
[menuController setTargetRect:menuFrame inView:cell];
[menuController setMenuVisible:YES animated:YES];
}
-(void)menuControllerWillHide:(NSNotification *)notification{
//re-register menuControllerWillShow
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuControllerWillShow:)
name:UIMenuControllerWillShowMenuNotification object:nil];
}
3) Implement tableView Delegates and implement these methods.
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
cell = (TableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
return YES;
}
-(BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
return NO;
}
- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
// required
}
4) Setup the cells (subclassing UITableViewCell) with
-(BOOL) canPerformAction:(SEL)action withSender:(id)sender {
return (action == @selector(copy:) || action == @selector(test:)); } /// this methods will be called for the cell menu items
-(void) test: (id) sender {
NSLog(@"test"); }
-(void) copy:(id)sender {
NSLog(@"copy"); }
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…