给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换个名字即可
************************************************************************************