Question

I have a UITableView that has a didSelectRow method... it creates a UIMenuController and displays it.

Currently, it works correctly but when the UIMenuController dismisses I wanted to call a [tableView1 deselectRowAtIndexPath:path1 animated:YES];

NSIndexPath *path1;
UITableView *table1;
#pragma maek - Table View
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{


    path1 = indexPath;

    tablview1 = tableview;

        CGRect location = [tableView rectForRowAtIndexPath:indexPath];

    location.origin.y = location.origin.y+30;

    [self becomeFirstResponder];

    UIMenuItem *menuItem = [[UIMenuItem alloc] initWithTitle:@"View Item" action:@selector(viewItem:)];
    UIMenuItem *menuItem1 = [[UIMenuItem alloc] initWithTitle:@"Edit Item" action:@selector(editItem:)];
    UIMenuItem *menuItem3 = [[UIMenuItem alloc] initWithTitle:@"Cancel" action:@selector(cancelSubMenu:)];

    UIMenuController *menuController = [UIMenuController sharedMenuController];
    [menuController setTargetRect:location inView:self.view];
    menuController.menuItems = [NSArray arrayWithObjects:menuItem, menuItem1,menuItem3, nil];

    menuController.arrowDirection = UIMenuControllerArrowUp;

    [menuController setMenuVisible:YES animated:YES];
}

-(IBAction)cancelSubMenu:(id)sender 
{
    [tableView1 deselectRowAtIndexPath:path1 animated:YES]; 
}

-(BOOL)canBecomeFirstResponder 
{
    return YES; 
}

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender 
{
    if(action == @selector(viewItem:)){return YES;}
    if(action == @selector(editItem:)){return YES;}
    if(action == @selector(cancelSubMenu:)){return YES;}

    return NO; 
}

When the user taps the cancel button on the UIMenuController the row is deselected properly. But when the user taps anywhere else on the screen the UIMenuControlller dismisses but the row is still selected.

Is there some kind of didDismiss UIMenuController method?

Was it helpful?

Solution

The UIMenuController will post a notification just after it hides called UIMenuControllerDidHideMenuNotification, you can subscribe to this notification to call a method that in turn calls deselectRowAtIndexPath on your table view. for example:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(yourMethodHere) name:UIMenuControllerDidHideMenuNotification object:nil];

And in Swift 5:

NotificationCenter.default.addObserver(self,
                                       selector: #selector(self.receiveNotification(_:)),
                                       name: UIMenuController.didShowMenuNotification,
                                       object: nil)

And to handle the notification:

@objc func receiveNotification(_ notification: Notification) {
    // do something here
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top