1. Menu所处的View必须实现 – (BOOL)canBecomeFirstResponder, 且返回YES 这个一定要返回YES
2. Menu所处的View必须实现 – (BOOL)canPerformAction:withSender, 并根据需求返回YES或NO
3. 使Menu所处的View成为First Responder (becomeFirstResponder)
4. 定位Menu (- setTargetRect:inView:)
5. 展示Menu (- setMenuVisible:animated:)
//
// ViewController.m
// UIMenuController
//
// Created by 陆巧怡 on 15/9/6.
// Copyright © 2015年 Simon. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) NSString *text;
@property (nonatomic, strong) UILabel *label;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.label = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 300, 30)];
self.label.text = @"点击出现UIMenuController";
self.label.userInteractionEnabled = YES;
[self.view addSubview:self.label];
UITapGestureRecognizer *touch = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
touch.numberOfTapsRequired = 1;
[self.label addGestureRecognizer:touch];
}
-(void)handleTap:(UIGestureRecognizer*) recognizer{
//是当前的对象成为第一响应者
[self becomeFirstResponder];
//创建UIMenuController的控件
UIMenuItem *flag = [[UIMenuItem alloc] initWithTitle:@"国旗" action:@selector(flag:)];
UIMenuItem *approve = [[UIMenuItem alloc] initWithTitle:@"Approve" action:@selector(approve:)];
UIMenuItem *deny = [[UIMenuItem alloc] initWithTitle:@"Deny" action:@selector(deny:)];
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setMenuVisible:NO];
[menu setMenuItems:[NSArray arrayWithObjects:flag, approve, deny, nil]];
[menu setTargetRect:self.label.frame inView:self.label.superview];
[menu setMenuVisible:YES animated:YES];
}
#pragma mark UIMenuController 控件方法
- (void)flag:(id)sender {
NSLog(@"国旗");
}
- (void)approve:(id)sender {
NSLog(@"Approve");
}
- (void)deny:(id)sender {
NSLog(@"Deny");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark 默认是为NO的。这里一定要设置成YES 要不然就不会出现
- (BOOL)canBecomeFirstResponder{
return YES;
}
//针对于copy的实现
-(void)copy:(id)sender{
//这里是粘贴板 可以复制文字,图片
UIPasteboard *pboard = [UIPasteboard generalPasteboard];
pboard.string = self.label.text;
}
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
//这里也是间接影响显示在UIMenuController的控件
if (action == @selector(copy:)) {
return YES;
}else if (action == @selector(flag:)){
return NO;
}else if (action == @selector(approve:)){
return YES;
}else if (action == @selector(deny:)){
return YES;
}else{
return [super canPerformAction:action withSender:sender];
}
}
@end