UIMenuController控件的使用

UIMenuController控件的使用

由于需求临时变更,同事写的自定义MenuController用不了了,只好用系统的MenuController,但在完成以下代码后,死活都调不出popMenu来:

UIMenuController *popMenu = [UIMenuController sharedMenuController];

  

UIMenuItem *item1 = [[UIMenuItem allocinitWithTitle:@”1″action:@selector(menuItem1Pressed:)];

UIMenuItem *item2 = [[UIMenuItem allocinitWithTitle:@”2″action:@selector(menuItem2Pressed:)];

UIMenuItem *item3 = [[UIMenuItem allocinitWithTitle:@”3″action:@selector(menuItem3Pressed:)];

UIMenuItem *item4 = [[UIMenuItem allocinitWithTitle:@”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个方法,缺一不可:


  1. becomFirstResponder方法,使view或者viewController的self成为第一响应者,可以在相应文件的任意地方调用实现该方法,不过建议与UIMenuController放在一起。[self becomeFirstResponder];
  2. 设置-(BOOL) canBecomeFirstResponder的返回值为YES,原因不言而喻。 -(BOOL) canBecomeFirstResponder{
    return YES;
    }
  3. 重载函数-(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:NO animated:YES];
    }
    如果将系统默认的菜单也显示出来,那么自定义的菜单将作为第二菜单,调用菜单时默认显示的是第一菜单,如果要直接显示第二菜单,根据cocoachina上一位同行总结出来的,先设置菜单可见性为NO即可:
    [popMenu setMenuVisible:NO animated:YES];

转载:http://blog.sina.com.cn/s/blog_8280f5ec0101h7ej.html


你可能感兴趣的:(UIMenuController控件的使用)