UILable加长按复制功能

给UILable添加长按复制功能以及需要注意的地方

// 初始化设置

- (void)pressAction {

self.contentLabel.userInteractionEnabled=YES;

UILongPressGestureRecognizer*longPress = [[UILongPressGestureRecognizeralloc]initWithTarget:selfaction:@selector(longPressAction:)];

longPress.minimumPressDuration=1;

[self.contentLabeladdGestureRecognizer:longPress];

}

// 使label能够成为响应事件

- (BOOL)canBecomeFirstResponder {

returnYES;

}

// 控制响应的方法

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {

returnaction ==@selector(customCopy:);

}

- (void)customCopy:(id)sender {

UIPasteboard*pasteboard = [UIPasteboardgeneralPasteboard];

pasteboard.string=self.contentLabel.text;

}

- (void)longPressAction:(UIGestureRecognizer*)recognizer {

if(recognizer.state==UIGestureRecognizerStateBegan) {

[self becomeFirstResponder];

UIMenuItem*copyItem = [[UIMenuItemalloc]initWithTitle:@"拷贝"action:@selector(customCopy:)];

[[UIMenuControllersharedMenuController]setMenuItems:[NSArrayarrayWithObjects:copyItem,nil]];

[[UIMenuControllersharedMenuController]setTargetRect:self.frameinView:self.superview];

[[UIMenuControllersharedMenuController]setMenuVisible:YESanimated:YES];

}

}

***************************************************************************************

注意⚠️:

1.recognizer.state==UIGestureRecognizerStateBegan防止多次出发

2.如果你的界面有inputView这个名称,长按触发的[self becomeFirstResponder]会导致崩溃,把inputView换个名字即可

************************************************************************************

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容