一.基本概念

UIKit框架中,可以直接执行拷贝黏贴操作的有:UITextView、UITextField和UIWebView,其他控件需要实现相关方法。

关于UIPasteboard

·黏贴板是app内或者app之间,交换数据的标准机制

·有公开的也有私有的,公开的黏贴板为系统级别(system pasteboard),私有的黏贴板为应用程序级别(app pasteboard),系统级别的黏贴板可以分享数据给任意其他app,应用程序级别的黏贴板只能分享给应用本身或者有相同team ID的应用

·system pasteboard默认是持久化的,所谓持久化,就是设备重启或者app卸载依然有效,app pasteboard默认是非持久化的,可以通过persistent修改

@property(getter=isPersistent,nonatomic) BOOL persistent;

一般使用名为UIPasteboardNameGeneral的system pasteboard,这货是个单例对象,是整个手机所有app共享的黏贴板

UIPasteboard *generalPasteboard = [UIPasteboard generalPasteboard];

二.具体实现

以label为例,假设label轻触两下或者长按显示编辑菜单

UIMenuController搭配UIPasteboard,执行拷贝-黏贴操作-b-LMLPHP

屏幕快照 2016-04-28 下午8.55.08.png

过程将会涉及

·UIPasteboard:提供黏贴板分享数据,从黏贴板读-写数据

·UIMenuController:展示编辑菜单,用来执行拷贝-黏贴操作

·UIResponder类的canPerformAction:withSender:方法,决定是否显示菜单某些命令,例如剪切

·UIResponderStandardEditActions非正式协议中声明了copy、cut、paste等方法,需要实现

:展示编辑菜单之前,系统会发送canPerformAction:withSender:消息给第一响应者,所以控件需要成为第一响应者来接收消息,并且在这个方法中,根据上下文的环境评估命令是否可用,例如当黏贴板没有可处理的数据时,响应者应该返回NO,阻止黏贴命令

0.首先打开用户交互,这个不要忘记,添加手势

- (void)awakeFromNib {    
   [super awakeFromNib];    
   UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(showMenu:)];    
   longPress.minimumPressDuration = 0.5;    
   [self addGestureRecognizer:longPress];
}  
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {    
   UITouch *touch = [touches anyObject];    
   if (touch.tapCount == 2) {          
       [self showMenu:nil];      
   }
}

1.是否可以成为第一响应者,默认为NO

- (BOOL)canBecomeFirstResponder {    
   return YES;
}

2.成为第一响应者

[self becomeFirstResponder];

3.创建编辑菜单

//获得单例对象UIMenuController *menu = [UIMenuController sharedMenuController];//view是参照物,指向以view为参照物的rect[menu setTargetRect:self.bounds inView:self];//显示[menu setMenuVisible:YES animated:YES];

4.实现canPerformAction:withSender:方法,参数action具体会有哪些方法,基本都在UIResponderStandardEditActions声明了

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {    
   NSLog(@"%@",NSStringFromSelector(action));    
   NSLog(@"%@",sender);    
   if (action == @selector(copy:) && self.text) {        //显示条件是文本不为空        
       return YES;      
   }    else if (action ==@selector(cut:) && self.text) {        //显示条件是文本不为空          
        return YES;      
   }    else if (action == @selector(paste:) && [UIPasteboard generalPasteboard].string) {        //显示条件是黏贴板不为空        
       return YES;      
   }    else {        
       return NO;      
   }
}

5.实现copy、cut、paste等方法

//实现剪切
- (void)cut:(id)sender {    
   [self copy:sender];    
   self.text = nil;
}
//实现拷贝
- (void)copy:(id)sender {    
   [UIPasteboard generalPasteboard].string = self.text;
}
//实现黏贴
- (void)paste:(id)sender {    
   UIPasteboard *generalPasteboard = [UIPasteboard generalPasteboard];    NSMutableArray *types = [[NSMutableArray alloc] init];    
   [types addObjectsFromArray:UIPasteboardTypeListString];    
   if ([generalPasteboard containsPasteboardTypes:types]) {        
       self.text = generalPasteboard.string;      
   }
}

6.如果想要添加自定义命令,可以创建UIMenuItem

//添加自定义菜单项
UIMenuItem *item = [[UIMenuItem alloc] initWithTitle:@"Change Color" action:@selector(changeColor:)];
menu.menuItems = @[item];

再以imageView为例,展示图片拷贝黏贴操作

#import "CustomImageView.h"@implementation CustomImageView- (void)awakeFromNib {    
   [super awakeFromNib];    
   UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(showMenu:)];    
   longPress.minimumPressDuration = 0.5;    
   [self addGestureRecognizer:longPress];
}  
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {    
   UITouch *touch = [touches anyObject];    
   if (touch.tapCount == 2) {          
       [self showMenu:nil];      
   }
}
/**  *  4.响应者是否可以执行该方法  *  *  @param action 方法  *  @param sender 请求对象  */
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {    
   if (action == @selector(copy:) && self.image) {        
       return YES;      
   }    else if (action == @selector(cut:) && self.image) {        
       return YES;      
   }    else if (action == @selector(paste:) && [UIPasteboard generalPasteboard].image) {        
       return YES;      
   }    else if (action == @selector(changeColor:)) {        
       return YES;      
   }    else {        
       return NO;      
   }
}
/**  *  1.是否可以成为第一响应者,默认为NO  *
/- (BOOL)canBecomeFirstResponder {    
return YES;
}  
- (void)showMenu:(UILongPressGestureRecognizer *)longPress {    
   if (longPress.state == UIGestureRecognizerStateEnded || longPress == nil) {        //2.成为第一响应者        
       [self becomeFirstResponder];        //添加自定义菜单项        
       UIMenuItem *item = [[UIMenuItem alloc] initWithTitle:@"Change Color" action:@selector(changeColor:)];        //3.创建编辑菜单        
       UIMenuController *menu = [UIMenuController sharedMenuController];        
       [menu setTargetRect:self.bounds inView:self];          
       menu.menuItems = @[item];          
       [menu setMenuVisible:YES animated:YES];      
   }
}  
- (void)cut:(id)sender {    
   [self copy:sender];    
   self.image = nil; }  
- (void)copy:(id)sender {    
   [UIPasteboard generalPasteboard].image = self.image;
}  
   - (void)paste:(id)sender {    
   UIPasteboard *generalPasteboard = [UIPasteboard generalPasteboard];    
   NSMutableArray *types = [[NSMutableArray alloc] init];    
   [types addObjectsFromArray:UIPasteboardTypeListImage];    
   if ([generalPasteboard containsPasteboardTypes:types]) {        
       self.image = generalPasteboard.image;      
   }
}  
- (void)changeColor:(id)sender {    
   self.backgroundColor = [UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0  blue:arc4random_uniform(256)/255.0  alpha:1.0];
}

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRT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cHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz6p+a6fAAAAD0lEQVR42mJ89/Y1QIABAAWXAsgVS/hWAAAAAElFTkSuQmCC" alt="" data-ratio="1.6079136690647482" data-src="http://mmbiz.qpic.cn/mmbiz/g4uoJOMA38LLFWhB4dvm9mtEdAwLxmoiaytJLSjtVbuSAKPeicp3CpAXZBLib0COTrgwZxl1iaMWIChoXBic9yk2kRQ/0?wx_fmt=png" data-type="png" data-w="" />

屏幕快照 2016-04-28 下午9.28.28.png

UIMenuController搭配UIPasteboard,执行拷贝-黏贴操作-b-LMLPHP

屏幕快照 2016-04-28 下午9.30.34.png

感谢分享

05-11 11:25