开发者

how to show UIMenuController to UIBarButtonItem

How to show UIMenuController under UIB开发者_高级运维arButtonItem when click it?


Assume your UIBarButtonItem has been connected to:

-(void)buttonClicked:(UIBarButtonItem*)sender event:(UIEvent*)event;

Then paste these codes into your view controller:

-(void)buttonClicked:(UIBarButtonItem*)sender event:(UIEvent*)event{
    [self becomeFirstResponder];

    /*get the view from the UIBarButtonItem*/
    UIView *buttonView=[[event.allTouches anyObject] view];
    CGRect buttonFrame=[buttonView convertRect:buttonView.frame toView:self.view];

    UIMenuController *menuController = [UIMenuController sharedMenuController];
    UIMenuItem *resetMenuItem = [[UIMenuItem alloc] initWithTitle:@"Menu Item" action:@selector(menuItemClicked:)];

    NSAssert([self becomeFirstResponder], @"Sorry, UIMenuController will not work with %@ since it cannot become first responder", self);
    [menuController setMenuItems:[NSArray arrayWithObject:resetMenuItem]];
    [menuController setTargetRect:buttonFrame inView:self.view];
    [menuController setMenuVisible:YES animated:YES];

    [resetMenuItem release];
}
- (void) copy:(id) sender {
    // called when copy clicked in menu
}
- (void) menuItemClicked:(id) sender {
    // called when Item clicked in menu
}
- (BOOL) canPerformAction:(SEL)selector withSender:(id) sender {
    if (selector == @selector(menuItemClicked:) /*|| selector == @selector(copy:)*/ /*<--enable that if you want the copy item */) {
        return YES;
    }
    return NO;
}
- (BOOL) canBecomeFirstResponder {
    return YES;
}

The key is to return YES for canBecomeFirstResponder and canPerformAction.

Here's the sample project if you need it.

These codes are actually come from other posts in stackoverflow, I just combined them.

Figure out UIBarButtonItem frame in window?

How to get UIMenuController work for a custom view?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜