// // UILabelCopy.m // smartRhino // // Created by niuzhen on 2020/2/7. // Copyright © 2020 tederen. All rights reserved. // #import "UILabelCopy.h" @interface UILabelCopy() @property (nonatomic, strong) UIPasteboard *pasteboard; @end @implementation UILabelCopy - (void)awakeFromNib { [super awakeFromNib]; self.numberOfLines = 0; self.pasteboard = [UIPasteboard generalPasteboard]; [self attachLongTapHandle]; } - (instancetype)init { if (self = [super init]) { self.numberOfLines = 0; self.pasteboard = [UIPasteboard generalPasteboard]; [self attachLongTapHandle]; } return self; } - (void)attachLongTapHandle { self.userInteractionEnabled = YES; UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc] initWithActionBlock:^(id _Nonnull sender) { UILongPressGestureRecognizer *press = (UILongPressGestureRecognizer *)sender; if (press.state == UIGestureRecognizerStateBegan) { // UILabel成为第一响应者 [self becomeFirstResponder]; UIMenuItem *copyMenuItem = [[UIMenuItem alloc]initWithTitle:@"复制" action:@selector(copyAction:)]; UIMenuItem *pasteMenueItem = [[UIMenuItem alloc]initWithTitle:@"全选" action:@selector(selectAll:)]; UIMenuItem *cutMenuItem = [[UIMenuItem alloc]initWithTitle:@"摘录" action:@selector(returnAction:)]; UIMenuController *menuVC = [UIMenuController sharedMenuController]; [menuVC setMenuItems:[NSArray arrayWithObjects:copyMenuItem, pasteMenueItem,cutMenuItem, nil]]; [menuVC setTargetRect:self.frame inView:self.superview]; [menuVC setMenuVisible:YES animated:YES]; } }]; [self addGestureRecognizer:longPress]; } - (BOOL)canBecomeFirstResponder { return YES; } - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { if (action == @selector(copyAction:)) { return YES; } if (action == @selector(selectAll:)) { return YES; } if (action == @selector(returnAction:)) { return YES; } return NO; } - (void)copyAction:(id)sender { NSLog(@"copy"); self.pasteboard.string = self.text; } - (void)selectAll:(id)sender { NSLog(@"selectAll"); } - (void)returnAction:(id)sender { NSLog(@"cut"); } @end