-
- (void)viewDidLoad {
-
[super viewDidLoad];
-
UIMenuItem *menuItem = [[UIMenuItem alloc] initWithTitle:@"分享到新浪微博" action:@selector(shareSina)];
-
UIMenuController *menu = [UIMenuController sharedMenuController];
-
[menu setMenuItems:[NSArray arrayWithObject:menuItem]];
-
[menuItem release];
-
}
-
-
- (void) shareSina {
-
NSLog(@"%@", [textview.text substringWithRange:textview.selectedRange]);
-
}
-
-
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender {
-
if(action == @selector(shareSina)) {
-
if(textview.selectedRange.length > 0)
-
return YES;
-
}
-
return NO;
-
}
=================
UIMenuController的使用
1. Menu所处的View必须实现 – (BOOL)canBecomeFirstResponder, 且返回YES
2. Menu所处的View必须实现 – (BOOL)canPerformAction:withSender, 并根据需求返回YES或NO
3. 使Menu所处的View成为First Responder (becomeFirstResponder)
4. 定位Menu (- setTargetRect:inView:)
5. 展示Menu (- setMenuVisible:animated:)
UIMenuController控件的使用
由于需求临时变更,同事写的自定义MenuController用不了了,只好用系统的MenuController,但在完成以下代码后,死活都调不出popMenu来:
UIMenuController *popMenu = [UIMenuController sharedMenuController];
UIMenuItem *item1 = [[UIMenuItem alloc] initWithTitle:@”1″action:@selector(menuItem1Pressed:)];
UIMenuItem *item2 = [[UIMenuItem alloc] initWithTitle:@”2″action:@selector(menuItem2Pressed:)];
UIMenuItem *item3 = [[UIMenuItem alloc] initWithTitle:@”3″action:@selector(menuItem3Pressed:)];
UIMenuItem *item4 = [[UIMenuItem alloc] initWithTitle:@”4″action:@selector(menuItem4Pressed:)];
NSArray *menuItems = [NSArray arrayWithObjects:item1,item2,item3,item4,nil];
[popMenu setMenuItems:menuItems];
[popMenu setArrowDirection:UIMenuControllerArrowDown];
[item4 release];
[item3 release];
[item2 release];
[item1 release];
[popMenu setTargetRect:CGRectMake(162,195,0,0) inView:self.dialView];
[popMenu setMenuVisible:YES animated:YES];
后来在StackOverFlow上看到这个问题,同时也在cocoachina上找到相应的方法,原来要想显示弹出菜单,必须实现3个方法,缺一不可:
becomFirstResponder方法,使view或者viewController的self成为第一响应者,可以在相应文件的任意地方调用实现该方法,不过建议与UIMenuController放在一起。
[self becomeFirstResponder];
设置-(BOOL) canBecomeFirstResponder的返回值为YES,原因不言而喻。
-(BOOL) canBecomeFirstResponder{
return YES;
}
重载函数-(BOOL) canPerfomAction:(SEL)action withSender:(id)sender,设置要显示的菜单项,返回值为YES。若不进行任何限制,则将显示系统自带的所有菜单项(很多的,自己可以试一下),在此,只显示自定义的4项,即:
-(BOOL) canPerformAction:(SEL)action withSender:(id)sender{
if (action == @selector(menuItem1Pressed:) || action ==@selector(menuItem2Pressed:) ||
action == @selector(menuItem3Pressed:) || action ==@selector(menuItem4Pressed:)) {
return YES;
}
return NO; //隐藏系统默认的菜单项
}
至于相应的菜单响应通过各selector函数来实现,如:
- (IBAction) menuItem1Pressed:(id)sender{
txtInputLabel.text = @”1″;
[[UIMenuController sharedMenuController] setMenuVisible:NOanimated:YES];
}
如果将系统默认的菜单也显示出来,那么自定义的菜单将作为第二菜单,调用菜单时默认显示的是第一菜单,如果要直接显示第二菜单,根据cocoachina上一位同行总结出来的经验,先设置菜单可见性为NO即可:
[popMenu setMenuVisible:NO animated:YES];