2

我针对同一个问题提到了关于 SO 的各种帖子。但仍然无法得到解决方案。

我有我所拥有的子。我的实现如下:UIButtonUILongGestureRecognizer

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
        [self addGestureRecognizer:longGesture];
    }
    return self;
}

- (BOOL)becomeFirstResponder
{
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    return YES;
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (void)longPress:(UILongPressGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateBegan)
    {
        NSLog(@"ButtonView: longPress: event called");
        UIMenuController *menu = [UIMenuController sharedMenuController];
        if (![menu isMenuVisible])
        {
            ButtonView *btn = (ButtonView *)gesture.view;
            if (![btn becomeFirstResponder])
            {
                NSLog(@"couldn't become first responder");
                return;
            }

            UIMenuItem *menuItem = [[UIMenuItem alloc] initWithTitle:@"Change Color" action:@selector(changeColor:)];
            UIMenuController *menuCont = [UIMenuController sharedMenuController];
            menuCont.arrowDirection = UIMenuControllerArrowDown;
            menuCont.menuItems = [NSArray arrayWithObject:menuItem];
            if([btn canBecomeFirstResponder])
            {
                [menuCont setTargetRect:btn.frame inView:btn.superview];
                [menuCont setMenuVisible:YES animated:YES];
                NSLog(@"menu visible....");
            }
        }
    }
    if (gesture.state == UIGestureRecognizerStateEnded || gesture.state == UIGestureRecognizerStateCancelled || gesture.state == UIGestureRecognizerStateFailed)
    {
        [self.layer setBorderColor:[UIColor clearColor].CGColor];
        [self.layer setBorderWidth:0.0];
    }
}

我有覆盖becomeFirstRespondercanBecomeFirstResponder.

重要提示:当我长按按钮时,我的日志消息“菜单可见....”被记录下来,但我看不到 UIMenuController 可见。

上面的代码中我还缺少什么吗?提前致谢。

4

1 回答 1

2

在显示菜单之前添加这一行:

[self becomeFirstResponder];

并删除此代码:

- (BOOL)becomeFirstResponder
{
    return YES;
}
于 2013-11-03T17:28:17.853 回答