我在视图控制器的- (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];
}
第一次选择一些文本时,菜单中包含“Read selected”菜单项,一切正常。但是,在后续文本选择中,菜单仅包含标准系统菜单项,如复制。粘贴等我已经检查了- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
方法,并且永远不会通过readSelectedText
操作调用它(就像第一次一样)。
知道为什么会这样吗?
答案 0 :(得分:1)
我尝试了下面的代码,它对我有用。点在菜单显示之前,添加自定义菜单项,然后自己显示菜单。
- (无效)viewDidLoad中 { [super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuWillShow) name:UIMenuControllerWillShowMenuNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuDidShow) name:UIMenuControllerDidShowMenuNotification object:nil];
}
- (无效)menuDidShow {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuWillShow) name:UIMenuControllerWillShowMenuNotification object:nil];
}
- (无效)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];
[menu setTargetRect:selectedRect inView:self.view]; //必须设置,否则菜单位置永远不会改变
[menu setMenuVisible:YES animated:YES];
}
答案 1 :(得分:1)
我的解决方案是基于qiufangzhou提供的建议,所以学分和接受的答案都归他所有。
无论如何,我最终订阅了UIMenuControllerWillShowMenuNotification
方法中的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];
}
诀窍在于,每次推送菜单时都必须添加自定义菜单项,而不仅仅是一次。我想每次都会清除自定义菜单项列表。
答案 2 :(得分:0)
对于谁可能仍然需要这个:
我们需要观察 UIMenuControllerDidHideMenuNotification 。
<强> viewDidApear:强>
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuDidHide) name:UIMenuControllerWillShowMenuNotification object:nil];
<强> viewDidDisapear:强>
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIMenuControllerDidHideMenuNotification object:nil];
<强> menuDidHide 强>
UIMenuItem *menuItem = [[UIMenuItem alloc] initWithTitle:@"Read selected" action:@selector(readSelectedText)];
[UIMenuController sharedMenuController].menuItems = [NSArray arrayWithObject:menuItem];