标签:
使用touchesEnded:withEvent:自定义复制粘贴菜单,copy:复制屏幕中的图片,cut:剪切屏幕中的图片,paste:粘贴屏幕中的图片.
1 @implementation prjCopyAndPaste 2 3 -(void)viewDidLoad 4 { 5 [super viewDidLoad]; 6 } 7 8 -(void)viewWillAppear:(BOOL)animated 9 { 10 [super viewWillAppear:animated]; 11 self.view.backgroundColor = [UIColor whiteColor]; 12 13 [self setupImageWithName:@"img_01" center:self.view.center]; 14 [self setupImageWithName:@"img_02" center:CGPointMake(200, 300)]; 15 [self setupImageWithName:@"img_03" center:CGPointMake(50, 80)]; 16 } 17 18 -(void)setupImageWithName:(NSString *)imageNamed center:(CGPoint)point 19 { 20 UIImageView *bug = [[UIImageView alloc]initWithImage:[UIImage imageNamed:imageNamed]]; 21 bug.center = point; 22 [self.view addSubview:bug]; 23 } 24 //成为第一响应者显示编辑菜单 25 -(BOOL)canBecomeFirstResponder 26 { 27 return YES; 28 } 29 30 -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 31 { 32 UITouch *touch = [touches anyObject]; 33 //连续两次触碰显示菜单 34 if ([self becomeFirstResponder] && 1 < [touch tapCount]) { 35 UIMenuController *menu = [UIMenuController sharedMenuController]; 36 self.touchPoint = [touch locationInView:self.view]; 37 CGRect minRect; 38 minRect.origin = self.touchPoint; 39 [menu setTargetRect:minRect inView:self.view]; 40 [menu setMenuVisible:YES animated:YES]; 41 } 42 } 43 44 -(BOOL)canPerformAction:(SEL)action withSender:(id)sender 45 { 46 if (@selector(copy:) == action) { 47 if ([self imageContainsPoint:self.touchPoint]) { 48 return YES; 49 } 50 }else if(@selector(cut:) == action){ 51 if ([self imageContainsPoint:self.touchPoint]) { 52 return YES; 53 } 54 }else if(@selector(paste:) == action){ 55 return (nil != [UIPasteboard generalPasteboard].image); 56 } 57 return NO; 58 } 59 60 -(UIImageView *)imageContainsPoint:(CGPoint)point 61 { 62 for (UIView *view in self.view.subviews) { 63 if (CGRectContainsPoint(view.frame, point)) { 64 if ([view isKindOfClass:[UIImageView class]]) { 65 return (UIImageView *)view; 66 } 67 } 68 } 69 return nil; 70 } 71 -(void)copy:(id)sender 72 { 73 UIImageView *imageView = [self imageContainsPoint:self.touchPoint]; 74 if (imageView) { 75 [UIPasteboard generalPasteboard].image = imageView.image; 76 } 77 } 78 -(void)cut:(id)sender 79 { 80 UIImageView *imageView = [self imageContainsPoint:self.touchPoint]; 81 if (imageView) { 82 [imageView removeFromSuperview]; 83 } 84 } 85 -(void)paste:(id)sender 86 { 87 UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; 88 if (pasteboard.image) { 89 UIImageView *bug = [[UIImageView alloc] initWithImage:pasteboard.image]; 90 bug.center = self.touchPoint; 91 [self.view addSubview:bug]; 92 pasteboard.image = bug.image; 93 } 94 } 95 96 97 @end
实现效果如图:
标签:
原文地址:http://www.cnblogs.com/runw/p/4687587.html