1

I have 2 viewControllers and in first one I'm using tapRecognizer to press and hold in order to show a UImenucontroller to copy a string. The tap is used for selecting the title on navigation bar, and it shows a UImenucontroller with copy item on it.

It works for the first time, but when user switch to another view controller and come back to the first view controller again, the menu does not show any more.

-(void)viewDidLoad{
    [super viewDidLoad];
    UIView *viewWithTitleLabel = self.navigationController.navigationBar.subviews[1];
    viewWithTitleLabel.userInteractionEnabled = YES;

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(topBarTitleTap:)];
    [viewWithTitleLabel addGestureRecognizer:longPress];
}

-(void)topBarTitleTap:(UILongPressGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
        UIMenuController *menuController = [UIMenuController sharedMenuController];
        [menuController setTargetRect:CGRectMake(CGRectGetMidX([self.view bounds]), -12.0, 0.0f, 0.0f) inView:self.view];
        [menuController setMenuVisible:YES animated:YES];
    }
}

- (void) copy:(id) sender {
    // called when copy clicked in tab bar title
    NSString *copyStringverse = self.navigationItem.title;
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    [pasteboard setString:copyStringverse];
}

- (BOOL) canBecomeFirstResponder {
    return YES;
}
Soheil
  • 5,054
  • 3
  • 24
  • 43
  • When I tried your code it didn't work at all. If I pass something like 40 instead of -12 for the y value in the setTargetRect: method, it works every time even after going to another controller and coming back. – rdelmar Jun 09 '14 at 05:08
  • this view is a subview and is embedded in a navigational view controller, that's why I've added -12. And is in correct position when it shows. – Soheil Jun 09 '14 at 06:41

2 Answers2

6

Add [self becomeFirstResponder]; before pop UIMenuController For example you can change your code as follow

-(void)topBarTitleTap:(UILongPressGestureRecognizer *)gestureRecognizer
{
    [self becomeFirstResponder];
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
        UIMenuController *menuController = [UIMenuController sharedMenuController];
        [menuController setTargetRect:CGRectMake(CGRectGetMidX([self.view bounds]), -12.0, 0.0f,     0.0f) inView:self.view];
        [menuController setMenuVisible:YES animated:YES];
    }
}

And don't forget to implement

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    //Customize your action if statement here
    return YES;
}

For your viewcontroller

Nathan Chang
  • 436
  • 2
  • 10
-1

Check if LongPressGestureRecognizer is working, every time.

I would place the gesturerecognizer code in viewDidAppear instead of ViewDidLoad, just to be safe

Debanjan
  • 99
  • 9