即使我阅读了您的所有答案,我也无法使其正常工作。我正在展示适用于所有人的现成代码。
假设我们有一个名为 Controller 的控制器类。您可以简单地将以下代码粘贴到此控制器,以使菜单在其视图上工作:
- (void)loadView {
[super loadView];
UILongPressGestureRecognizer *gr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[self.view addGestureRecognizer:gr];
}
- (void) longPress:(UILongPressGestureRecognizer *) gestureRecognizer {
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
CGPoint location = [gestureRecognizer locationInView:[gestureRecognizer view]];
UIMenuController *menuController = [UIMenuController sharedMenuController];
UIMenuItem *resetMenuItem = [[UIMenuItem alloc] initWithTitle:@"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:CGRectMake(location.x, location.y, 0.0f, 0.0f) inView:[gestureRecognizer view]];
[menuController setMenuVisible:YES animated:YES];
}
}
- (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:)) {
return YES;
}
return NO;
}
- (BOOL) canBecomeFirstResponder {
return YES;
}
为了使菜单工作,必须做的是 firstResponder(在我们的例子中,我们的控制器 - 参见 [self becomeFirstResponder] 行)必须能够成为第一响应者(覆盖方法 canBecomeFirstResponder 导致默认实现返回 NO)以及因为- (BOOL) canPerformAction:(SEL)selector withSender:(id) sender
这应该对可以执行的任何操作返回 YESfirstResponder