更改视图控制器后,UIMenuController不显示

时间:2014-06-09 04:30:12

标签: ios objective-c xcode uiviewcontroller uimenucontroller

我有2个viewControllers,在第一个我使用tapRecognizer按住以显示UImenucontroller来复制字符串。点击用于在导航栏上选择标题,它显示一个带有复制项目的UI菜单控制器。

适用于第一次时间,但当用户切换到另一个视图控制器并再次返回第一个视图控制器时,菜单不再显示。

-(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;
}

2 个答案:

答案 0 :(得分:6)

添加[self becomeFirstResponder];在流行UIMenuController之前 例如,您可以按照以下更改代码

-(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];
    }
}

不要忘记实施

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

对于你的viewcontroller

答案 1 :(得分:-1)

每次检查LongPressGestureRecognizer是否正常工作。

我会将gesturerecognizer代码放在viewDidAppear而不是ViewDidLoad中,只是为了安全