• iOS开发_iphone 实现剪贴板操作_iphone 复制粘贴功能(转)


    在iOS中,可以使用剪贴板实现应用程序之中以及应用程序之间实现数据的共享。比如你可以从iPhone QQ复制一个url,然后粘贴到safari浏览器中查看这个链接的内容。

    一、在iOS中下面三个控件,自身就有复制-粘贴的功能:

    1、UITextView
    2、UITextField
    3、UIWebView

    二、UIKit framework提供了几个类和协议方便我们在自己的应用程序中实现剪贴板的功能。

    1、UIPasteboard:我们可以向其中写入数据,也可以读取数据

    2、UIMenuController:显示一个快捷菜单,用来复制、剪贴、粘贴选择的项。

    3、UIResponder中的 canPerformAction:withSender:用于控制哪些命令显示在快捷菜单中。

    4、当快捷菜单上的命令点击的时候,UIResponderStandardEditActions将会被调用。

    三、下面这些项能被放置到剪贴板中

    1、UIPasteboardTypeListString —  字符串数组, 包含kUTTypeUTF8PlainText
    2、UIPasteboardTypeListURL —   URL数组,包含kUTTypeURL
    3、UIPasteboardTypeListImage —   图形数组, 包含kUTTypePNG 和kUTTypeJPEG
    4、UIPasteboardTypeListColor —   颜色数组

    四、剪贴板的类型分为两种:

    系统级:使用UIPasteboardNameGeneral和UIPasteboardNameFind创建,系统级的剪贴板,当应用程序关闭,或者卸载时,数据都不会丢失。

    应用程序级:通过设置,可以让数据在应用程序关闭之后仍然保存在剪贴板中,但是应用程序卸载之后数据就会失去。我们可用通过pasteboardWithName:create:来创建。

    了解这些之后,下面通过一系列的例子来说明如何在应用程序中使用剪贴板

     

     

    例子:

    1、复制剪贴文本。

        下面通过一个例子,可以在tableview上显示一个快捷菜单,上面只有复制按钮,复制tableview上的数据之后,然后粘贴到title上。

    定义一个单元格类CopyTableViewCell,在这个类的上显示快捷菜单,实现复制功能。

    1. @interface CopyTableViewCell : UITableViewCell {       
    2.     id delegate;   
    3. }   
    4. @property (nonatomic, retain) id delegate;   
    5. @end  
    @interface CopyTableViewCell : UITableViewCell {     
    	id delegate; 
    } 
    @property (nonatomic, retain) id delegate; 
    @end

    //实现CopyTableViewCell :

    1. #import "CopyTableViewCell.h"    
    2. @implementation CopyTableViewCell    
    3. @synthesize delegate;    
    4. - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {       
    5.     if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {     }      
    6.     return self;   
    7. }   
    8.   
    9. - (void)setSelected:(BOOL)selected animated:(BOOL)animated {      
    10.     [super setSelected:selected animated:animated]; }   
    11.   
    12. - (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {       
    13.     [[self delegate] performSelector:@selector(showMenu:) withObject:self afterDelay:0.9f];            
    14.     [super setHighlighted:highlighted animated:animated];    
    15. }   
    16. - (BOOL)canBecomeFirstResponder  {      
    17.     return YES;   
    18. }   
    19.   
    20. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender{       
    21.     if (action == @selector(cut:)){           
    22.         return NO;       
    23.     }else if(action == @selector(copy:)){           
    24.             return YES;       
    25.     } else if(action == @selector(paste:)){           
    26.             return NO;       
    27.     } else if(action == @selector(select:)){           
    28.             return NO;       
    29.     }      else if(action == @selector(selectAll:)){           
    30.             return NO;       
    31.     }     else      {           
    32.     return [super canPerformAction:action withSender:sender];      
    33.     }   
    34. }   
    35. - (void)copy:(id)sender {       
    36.     UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];       
    37.     [pasteboard setString:[[self textLabel]text]]; }   
    38. - (void)dealloc {       
    39.     [super dealloc];   
    40. }   
    41. @end  
    42.    
    43. //定义CopyPasteTextController,实现粘贴功能。   
    44. @interface CopyPasteTextController : UIViewController<UITableViewDelegate> {       
    45.     //用来标识是否显示快捷菜单        
    46.     BOOL menuVisible;       
    47.     UITableView *tableView;   
    48. }    
    49. @property (nonatomic, getter=isMenuVisible) BOOL menuVisible;    
    50. @property (nonatomic, retain) IBOutlet UITableView *tableView;   
    51. @end   
    #import "CopyTableViewCell.h" 
    @implementation CopyTableViewCell  
    @synthesize delegate;  
    - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {     
    	if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {     }    
     	return self; 
    } 
    
    - (void)setSelected:(BOOL)selected animated:(BOOL)animated {    
     	[super setSelected:selected animated:animated]; } 
    
    - (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {     
    	[[self delegate] performSelector:@selector(showMenu:) withObject:self afterDelay:0.9f];          
    	[super setHighlighted:highlighted animated:animated];  
    } 
    - (BOOL)canBecomeFirstResponder  {    
     	return YES; 
    } 
    
    - (BOOL)canPerformAction:(SEL)action withSender:(id)sender{     
    	if (action == @selector(cut:)){         
    		return NO;     
    	}else if(action == @selector(copy:)){         
    			return YES;     
    	} else if(action == @selector(paste:)){         
    			return NO;     
    	} else if(action == @selector(select:)){         
    			return NO;     
    	}      else if(action == @selector(selectAll:)){         
    			return NO;     
    	}     else      {         
    	return [super canPerformAction:action withSender:sender];    
     	} 
    } 
    - (void)copy:(id)sender {     
    	UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];     
    	[pasteboard setString:[[self textLabel]text]]; } 
    - (void)dealloc {     
    	[super dealloc]; 
    } 
    @end
     
    //定义CopyPasteTextController,实现粘贴功能。
    @interface CopyPasteTextController : UIViewController<UITableViewDelegate> {     
    	//用来标识是否显示快捷菜单     
    	BOOL menuVisible;     
    	UITableView *tableView; 
    }  
    @property (nonatomic, getter=isMenuVisible) BOOL menuVisible;  
    @property (nonatomic, retain) IBOutlet UITableView *tableView; 
    @end 

    实现CopyPasteTextController :

    1. #import "CopyPasteTextController.h"    
    2. #import "CopyTableViewCell.h"     
    3. @implementation CopyPasteTextController   
    4. @synthesize menuVisible,tableView;   
    5. - (void)viewDidLoad {       
    6. [super viewDidLoad];       
    7. [self setTitle:@"文字复制粘贴"];       
    8. //点击这个按钮将剪贴板的内容粘贴到title上        
    9. UIBarButtonItem *addButton = [[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh                                                   target:self                                         
    10.                             action:@selector(readFromPasteboard:)]autorelease];       
    11.     [[self navigationItem] setRightBarButtonItem:addButton];   
    12. }     
    13.   
    14. // Customize the number of sections in the table view.    
    15. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {       
    16.     return 1;   
    17. }    
    18.   
    19. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {       
    20.     return 9;   
    21. }    
    22. // Customize the appearance of table view cells.    
    23. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {       
    24.     static NSString *CellIdentifier =@"Cell";       
    25.     CopyTableViewCell *cell = (CopyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];       
    26.     if (cell == nil) {           
    27.         cell = [[[CopyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];           
    28.     [cell setDelegate:self];       
    29.     }            
    30.     // Configure the cell.        
    31.     NSString *text = [NSString stringWithFormat:@"Row %d", [indexPath row]];       
    32.     [[cell textLabel] setText:text];       
    33.     return cell;   
    34. }    
    35.   
    36. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {       
    37.     if([self isMenuVisible])     {           
    38.     return;       
    39. }       
    40.     [[[self tableView] cellForRowAtIndexPath:indexPath] setSelected:YES  animated:YES];   
    41. }   
    42.   
    43. //显示菜单    
    44. - (void)showMenu:(id)cell {       
    45.     if ([cell isHighlighted]) {           
    46.     [cell becomeFirstResponder];                    
    47.     UIMenuController * menu = [UIMenuController sharedMenuController];           
    48.     [menu setTargetRect: [cell frame] inView: [self view]];           
    49.     [menu setMenuVisible: YES animated: YES];       
    50. }   
    51. }   
    52.   
    53. - (void)readFromPasteboard:(id)sender {       
    54.     [self setTitle:[NSString stringWithFormat:@"Pasteboard = %@",                          
    55.     [[UIPasteboard generalPasteboard] string]]];   
    56. }    
    57. - (void)didReceiveMemoryWarning {       
    58. // Releases the view if it doesn't have a superview.        
    59.     [super didReceiveMemoryWarning];            
    60. // Relinquish ownership any cached data, images, etc that aren't in use.    
    61. }    
    62.   
    63. - (void)viewDidUnload {       
    64.     [super viewDidUnload];       
    65.     [self.tableView release];            
    66. // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.        
    67. // For example: self.myOutlet = nil;    
    68. }  
    #import "CopyPasteTextController.h" 
    #import "CopyTableViewCell.h"  
    @implementation CopyPasteTextController 
    @synthesize menuVisible,tableView; 
    - (void)viewDidLoad {     
    [super viewDidLoad];     
    [self setTitle:@"文字复制粘贴"];     
    //点击这个按钮将剪贴板的内容粘贴到title上     
    UIBarButtonItem *addButton = [[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh                                      			 target:self                                       
    							action:@selector(readFromPasteboard:)]autorelease];     
    	[[self navigationItem] setRightBarButtonItem:addButton]; 
    }   
    
    // Customize the number of sections in the table view. 
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {     
    	return 1; 
    }  
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {     
    	return 9; 
    }  
    // Customize the appearance of table view cells. 
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {     
    	static NSString *CellIdentifier =@"Cell";     
    	CopyTableViewCell *cell = (CopyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];     
    	if (cell == nil) {         
    		cell = [[[CopyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];         
    	[cell setDelegate:self];     
    	}          
    	// Configure the cell.     
    	NSString *text = [NSString stringWithFormat:@"Row %d", [indexPath row]];     
    	[[cell textLabel] setText:text];     
    	return cell; 
    }  
    
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {     
    	if([self isMenuVisible])     {         
    	return;     
    }     
    	[[[self tableView] cellForRowAtIndexPath:indexPath] setSelected:YES  animated:YES]; 
    } 
    
    //显示菜单 
    - (void)showMenu:(id)cell {     
    	if ([cell isHighlighted]) {         
    	[cell becomeFirstResponder];                  
    	UIMenuController * menu = [UIMenuController sharedMenuController];         
    	[menu setTargetRect: [cell frame] inView: [self view]];         
    	[menu setMenuVisible: YES animated: YES];     
    } 
    } 
    
    - (void)readFromPasteboard:(id)sender {     
    	[self setTitle:[NSString stringWithFormat:@"Pasteboard = %@",                        
    	[[UIPasteboard generalPasteboard] string]]]; 
    }  
    - (void)didReceiveMemoryWarning {     
    // Releases the view if it doesn't have a superview.     
    	[super didReceiveMemoryWarning];          
    // Relinquish ownership any cached data, images, etc that aren't in use. 
    }  
    
    - (void)viewDidUnload {     
    	[super viewDidUnload];     
    	[self.tableView release];          
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.     
    // For example: self.myOutlet = nil; 
    }

    效果:

    复制一行数据:

    点击右上角的按钮粘贴,将数据显示在title上:

    2、图片复制粘贴

       下面通过一个例子,将图片复制和剪贴到另外一个UIImageView中间。

    1、在界面上放置两个uiimageview,一个是图片的数据源,一个是将图片粘贴到的地方。CopyPasteImageViewController 代码如下:

    1. @interface CopyPasteImageViewController : UIViewController {       
    2.     UIImageView *imageView;       
    3.     UIImageView *pasteView;       
    4.     UIImageView *selectedView;   
    5. }   
    6. @property (nonatomic, retain) IBOutlet UIImageView *imageView;   
    7. @property (nonatomic, retain) IBOutlet UIImageView *pasteView;   
    8. @property (nonatomic, retain) UIImageView *selectedView;   
    9. - (void)placeImageOnPasteboard:(id)view;   
    10. @end  
    @interface CopyPasteImageViewController : UIViewController {     
    	UIImageView *imageView;     
    	UIImageView *pasteView;     
    	UIImageView *selectedView; 
    } 
    @property (nonatomic, retain) IBOutlet UIImageView *imageView; 
    @property (nonatomic, retain) IBOutlet UIImageView *pasteView; 
    @property (nonatomic, retain) UIImageView *selectedView; 
    - (void)placeImageOnPasteboard:(id)view; 
    @end

    2、当触摸图片的时候我们显示快捷菜单:

    1. - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {       
    2.     NSSet *copyTouches = [event touchesForView:imageView];       
    3.     NSSet *pasteTouches = [event touchesForView:pasteView];            
    4.     [self becomeFirstResponder];       
    5.     if ([copyTouches count] > 0) {           
    6.         [self performSelector:@selector(showMenu:) withObject:imageView afterDelay:0.9f];       
    7.     }     else  if([pasteTouches count] > 0) {           
    8.         [self performSelector:@selector(showMenu:) withObject:pasteView afterDelay:0.9f];       
    9.     }       
    10.     [super touchesBegan:touches withEvent:event];   
    11. }    
    12.   
    13. - (void)showMenu:(id)view {       
    14.     [self setSelectedView:view];            
    15.     UIMenuController * menu = [UIMenuController sharedMenuController];       
    16.     [menu setTargetRect: CGRectMake(5, 10, 1, 1) inView: view];       
    17.     [menu setMenuVisible: YES animated: YES];   
    18. }  
    19.   
    20. 这里的快捷菜单,显示三个菜单项:剪贴、粘贴、复制:  
    21. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender{       
    22.     if (action == @selector(cut:)) {         return ([self selectedView] == imageView) ? YES : NO;       
    23.     } else if (action == @selector(copy:)) {        return ([self selectedView] == imageView) ? YES : NO;       
    24.     } else if (action == @selector(paste:)) {         return ([self selectedView] == pasteView) ? YES : NO;       
    25.     } else if (action == @selector(select:)) {         return NO;       
    26.     } else if (action == @selector(selectAll:)) {           
    27.         return NO;      
    28.     } else {           
    29.         return [super canPerformAction:action withSender:sender];       
    30.     }   
    31. }   
    32.   
    33. - (void)cut:(id)sender {       
    34.     [self copy:sender];       
    35.     [imageView setHidden:YES];   
    36. }   
    37.   
    38. - (void)copy:(id)sender {       
    39.     [self placeImageOnPasteboard:[self imageView]]; }   
    40.   
    41. - (void)paste:(id)sender {       
    42.     UIPasteboard *appPasteBoard =      [UIPasteboard pasteboardWithName:@"CopyPasteImage" create:YES];       
    43.     NSData *data =[appPasteBoard dataForPasteboardType:@"com.marizack.CopyPasteImage.imageView"];       
    44.     pasteView.image = [UIImage imageWithData:data]; }  
    - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {     
    	NSSet *copyTouches = [event touchesForView:imageView];     
    	NSSet *pasteTouches = [event touchesForView:pasteView];          
    	[self becomeFirstResponder];     
    	if ([copyTouches count] > 0) {         
    		[self performSelector:@selector(showMenu:) withObject:imageView afterDelay:0.9f];     
    	}     else  if([pasteTouches count] > 0) {         
    		[self performSelector:@selector(showMenu:) withObject:pasteView afterDelay:0.9f];     
    	}     
    	[super touchesBegan:touches withEvent:event]; 
    }  
    
    - (void)showMenu:(id)view {     
    	[self setSelectedView:view];          
    	UIMenuController * menu = [UIMenuController sharedMenuController];     
    	[menu setTargetRect: CGRectMake(5, 10, 1, 1) inView: view];     
    	[menu setMenuVisible: YES animated: YES]; 
    }
    
    这里的快捷菜单,显示三个菜单项:剪贴、粘贴、复制:
    - (BOOL)canPerformAction:(SEL)action withSender:(id)sender{     
    	if (action == @selector(cut:)) {         return ([self selectedView] == imageView) ? YES : NO;     
    	} else if (action == @selector(copy:)) {        return ([self selectedView] == imageView) ? YES : NO;     
    	} else if (action == @selector(paste:)) {         return ([self selectedView] == pasteView) ? YES : NO;     
    	} else if (action == @selector(select:)) {         return NO;     
    	} else if (action == @selector(selectAll:)) {         
    		return NO;    
     	} else {         
    		return [super canPerformAction:action withSender:sender];     
    	} 
    } 
    
    - (void)cut:(id)sender {     
    	[self copy:sender];     
    	[imageView setHidden:YES]; 
    } 
    
    - (void)copy:(id)sender {     
    	[self placeImageOnPasteboard:[self imageView]]; } 
    
    - (void)paste:(id)sender {     
    	UIPasteboard *appPasteBoard =      [UIPasteboard pasteboardWithName:@"CopyPasteImage" create:YES];     
    	NSData *data =[appPasteBoard dataForPasteboardType:@"com.marizack.CopyPasteImage.imageView"];     
    	pasteView.image = [UIImage imageWithData:data]; }

    效果:

    1、点击图片,显示菜单按钮。

    2、点击复制,将数据复制到剪贴板上:

    3、点击粘贴,将数据粘贴到uiimageview上。

  • 相关阅读:
    禁止页面被复制和禁止右键,一段样式一段JS就行了,无需复杂设定!
    你不知道的DIV+CSS的命名规则
    帝国cms提高网站网页打开速度的手段
    帝国cms网站管理系统之安全设置最优化分享
    渗透测试===使用BURPSUIT暴力破解某网站的手机验证码
    并发、并行、同步、异步、多线程的区别?
    python基础===一行 Python 代码实现并行(转)
    python目前安装的包备份
    jmeter,测登录,要不要过滤掉JS,CSS等请求?感觉过滤掉了压出来的数据就不真实?
    几个网站
  • 原文地址:https://www.cnblogs.com/lzjsky/p/2966223.html
Copyright © 2020-2023  润新知