2

- (void)viewDidLoad我在视图控制器的方法中添加了一个自定义菜单:

UIMenuItem *menuItem = [[UIMenuItem alloc] initWithTitle:@"Read selected" action:@selector(readSelectedText)];
[UIMenuController sharedMenuController].menuItems = [NSArray arrayWithObject:menuItem];

在同一个控制器中,我还实现了该方法:

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(readSelectedText)) {
        if (textView.selectedRange.length > 0) {
            return YES;
        }
        return NO;
    }
    return [super canPerformAction:action withSender:sender];
}

我第一次选择一些文本时,菜单包含“读取所选”菜单项,并且一切正常。然而,在随后的文本选择中,菜单仅包含标准系统菜单项,如复制。paste等- (BOOL)canPerformAction:(SEL)action withSender:(id)sender_readSelectedText

知道为什么会这样吗?

4

3 回答 3

1

我试过下面的代码,它对我有用。重点是在菜单显示之前,添加自定义菜单项,然后自己显示菜单。

-(void)viewDidLoad { [超级 viewDidLoad];

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuWillShow) name:UIMenuControllerWillShowMenuNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuDidShow) name:UIMenuControllerDidShowMenuNotification object:nil];

}

-(void)menuDidShow{

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuWillShow) name:UIMenuControllerWillShowMenuNotification object:nil];

}

-(void)menuWillShow{

UIMenuItem *shareMenu = [[UIMenuItem alloc] initWithTitle:@"微博分享" action:@selector(shareToWeibo:)];
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setMenuItems:[NSArray arrayWithObjects:shareMenu, nil]];

[[NSNotificationCenter defaultCenter] removeObserver:self name:UIMenuControllerWillShowMenuNotification object:nil];

[菜单 setTargetRect:selectedRect inView:self.view]; //必须设置,否则菜单位置永远不会改变

[menu setMenuVisible:YES animated:YES];

}

于 2012-12-06T10:07:34.373 回答
1

我的解决方案是基于 qiufangzhou 提供的建议,因此学分和接受的答案都归他所有。

无论如何,我最终UIMenuControllerWillShowMenuNotification在我的方法中订阅了 noritication viewDidLoad

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuWillShow) name:UIMenuControllerWillShowMenuNotification object:nil];

然后我实现了这个方法:

-(void)menuWillShow{
    UIMenuItem *menuItem = [[UIMenuItem alloc] initWithTitle:@"Read selected" action:@selector(readSelectedText)];
    [UIMenuController sharedMenuController].menuItems = [NSArray arrayWithObject:menuItem];
}

诀窍是每次推送菜单时都必须添加自定义菜单项,而不仅仅是一次。我猜自定义菜单项列表每次都会被清除。

于 2012-12-06T13:33:14.690 回答
0

对于可能仍然需要这个的人:

我们只需要观察UIMenuControllerDidHideMenuNotification 即可

viewDidApear:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuDidHide) name:UIMenuControllerWillShowMenuNotification object:nil];

viewDidDisapear:

[[NSNotificationCenter defaultCenter] removeObserver:self name:UIMenuControllerDidHideMenuNotification object:nil];

菜单隐藏

UIMenuItem *menuItem = [[UIMenuItem alloc] initWithTitle:@"Read selected" action:@selector(readSelectedText)];
[UIMenuController sharedMenuController].menuItems = [NSArray arrayWithObject:menuItem];
于 2016-03-14T19:51:46.567 回答