標籤:
使用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)point19 {20 UIImageView *bug = [[UIImageView alloc]initWithImage:[UIImage imageNamed:imageNamed]];21 bug.center = point;22 [self.view addSubview:bug];23 }24 //成為第一響應者顯示編輯菜單25 -(BOOL)canBecomeFirstResponder26 {27 return YES;28 }29 30 -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event31 {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)sender45 {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)point61 {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)sender72 {73 UIImageView *imageView = [self imageContainsPoint:self.touchPoint];74 if (imageView) {75 [UIPasteboard generalPasteboard].image = imageView.image;76 }77 }78 -(void)cut:(id)sender79 {80 UIImageView *imageView = [self imageContainsPoint:self.touchPoint];81 if (imageView) {82 [imageView removeFromSuperview];83 }84 }85 -(void)paste:(id)sender86 {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 @endView Code
實現效果
複製/剪下/粘貼螢幕中的圖片