天天看點

iOS實作剪貼闆操作

在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,在這個類的上顯示快捷菜單,實作複制功能。

[cpp]  view plain copy print ?

  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 :

[cpp]  view plain copy print ?

  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. - (void)setSelected:(BOOL)selected animated:(BOOL)animated {      
  9.     [super setSelected:selected animated:animated]; }   
  10. - (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {       
  11.     [[self delegate] performSelector:@selector(showMenu:) withObject:self afterDelay:0.9f];            
  12.     [super setHighlighted:highlighted animated:animated];    
  13. }   
  14. - (BOOL)canBecomeFirstResponder  {      
  15.     return YES;   
  16. }   
  17. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender{       
  18.     if (action == @selector(cut:)){           
  19.         return NO;       
  20.     }else if(action == @selector(copy:)){           
  21.             return YES;       
  22.     } else if(action == @selector(paste:)){           
  23.             return NO;       
  24.     } else if(action == @selector(select:)){           
  25.             return NO;       
  26.     }      else if(action == @selector(selectAll:)){           
  27.             return NO;       
  28.     }     else      {           
  29.     return [super canPerformAction:action withSender:sender];      
  30.     }   
  31. }   
  32. - (void)copy:(id)sender {       
  33.     UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];       
  34.     [pasteboard setString:[[self textLabel]text]]; }   
  35. - (void)dealloc {       
  36.     [super dealloc];   
  37. }   
  38. @end  
  39. //定義CopyPasteTextController,實作粘貼功能。   
  40. @interface CopyPasteTextController : UIViewController<UITableViewDelegate> {       
  41.     //用來辨別是否顯示快捷菜單        
  42.     BOOL menuVisible;       
  43.     UITableView *tableView;   
  44. }    
  45. @property (nonatomic, getter=isMenuVisible) BOOL menuVisible;    
  46. @property (nonatomic, retain) IBOutlet UITableView *tableView;   
  47. @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 :

[cpp]  view plain copy print ?

  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. // Customize the number of sections in the table view.    
  14. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {       
  15.     return 1;   
  16. }    
  17. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {       
  18.     return 9;   
  19. }    
  20. // Customize the appearance of table view cells.    
  21. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {       
  22.     static NSString *CellIdentifier [email protected]"Cell";       
  23.     CopyTableViewCell *cell = (CopyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];       
  24.     if (cell == nil) {           
  25.         cell = [[[CopyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];           
  26.     [cell setDelegate:self];       
  27.     }            
  28.     // Configure the cell.        
  29.     NSString *text = [NSString stringWithFormat:@"Row %d", [indexPath row]];       
  30.     [[cell textLabel] setText:text];       
  31.     return cell;   
  32. }    
  33. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {       
  34.     if([self isMenuVisible])     {           
  35.     return;       
  36. }       
  37.     [[[self tableView] cellForRowAtIndexPath:indexPath] setSelected:YES  animated:YES];   
  38. }   
  39. //顯示菜單    
  40. - (void)showMenu:(id)cell {       
  41.     if ([cell isHighlighted]) {           
  42.     [cell becomeFirstResponder];                    
  43.     UIMenuController * menu = [UIMenuController sharedMenuController];           
  44.     [menu setTargetRect: [cell frame] inView: [self view]];           
  45.     [menu setMenuVisible: YES animated: YES];       
  46. }   
  47. }   
  48. - (void)readFromPasteboard:(id)sender {       
  49.     [self setTitle:[NSString stringWithFormat:@"Pasteboard = %@",                          
  50.     [[UIPasteboard generalPasteboard] string]]];   
  51. }    
  52. - (void)didReceiveMemoryWarning {       
  53. // Releases the view if it doesn't have a superview.        
  54.     [super didReceiveMemoryWarning];            
  55. // Relinquish ownership any cached data, images, etc that aren't in use.    
  56. }    
  57. - (void)viewDidUnload {       
  58.     [super viewDidUnload];       
  59.     [self.tableView release];            
  60. // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.        
  61. // For example: self.myOutlet = nil;    
  62. }  
#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 [email protected]"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; 
}
           

效果:

複制一行資料:

iOS實作剪貼闆操作

點選右上角的按鈕粘貼,将資料顯示在title上:

iOS實作剪貼闆操作

2、圖檔複制粘貼

   下面通過一個例子,将圖檔複制和剪貼到另外一個UIImageView中間。

1、在界面上放置兩個uiimageview,一個是圖檔的資料源,一個是将圖檔粘貼到的地方。CopyPasteImageViewController 代碼如下:

[cpp]  view plain copy print ?

  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、當觸摸圖檔的時候我們顯示快捷菜單:

[cpp]  view plain copy print ?

  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. - (void)showMenu:(id)view {       
  13.     [self setSelectedView:view];            
  14.     UIMenuController * menu = [UIMenuController sharedMenuController];       
  15.     [menu setTargetRect: CGRectMake(5, 10, 1, 1) inView: view];       
  16.     [menu setMenuVisible: YES animated: YES];   
  17. }  
  18. 這裡的快捷菜單,顯示三個菜單項:剪貼、粘貼、複制:  
  19. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender{       
  20.     if (action == @selector(cut:)) {         return ([self selectedView] == imageView) ? YES : NO;       
  21.     } else if (action == @selector(copy:)) {        return ([self selectedView] == imageView) ? YES : NO;       
  22.     } else if (action == @selector(paste:)) {         return ([self selectedView] == pasteView) ? YES : NO;       
  23.     } else if (action == @selector(select:)) {         return NO;       
  24.     } else if (action == @selector(selectAll:)) {           
  25.         return NO;      
  26.     } else {           
  27.         return [super canPerformAction:action withSender:sender];       
  28.     }   
  29. }   
  30. - (void)cut:(id)sender {       
  31.     [self copy:sender];       
  32.     [imageView setHidden:YES];   
  33. }   
  34. - (void)copy:(id)sender {       
  35.     [self placeImageOnPasteboard:[self imageView]]; }   
  36. - (void)paste:(id)sender {       
  37.     UIPasteboard *appPasteBoard =      [UIPasteboard pasteboardWithName:@"CopyPasteImage" create:YES];       
  38.     NSData *data =[appPasteBoard dataForPasteboardType:@"com.marizack.CopyPasteImage.imageView"];       
  39.     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、點選圖檔,顯示菜單按鈕。

iOS實作剪貼闆操作

2、點選複制,将資料複制到剪貼闆上:

iOS實作剪貼闆操作

3、點選粘貼,将資料粘貼到uiimageview上。

iOS實作剪貼闆操作