目前iOS上自帶支持拷貝黏貼的控件主要是:UITextField,UITextView,UIWebView
然而在很多情況下我們也會(huì)遇到需要在某些顯示Label中支持長按復(fù)制的功能,如果需要做到拷貝這一點(diǎn),我們需要自定義一個(gè)繼承UILabel的控件,具體代碼如下:
//
// CopyEnableLabel.m
// ReachjunctionProject
//
// Created by Xiao on 2019/6/21.
// Copyright ? 2019 Reachjunction. All rights reserved.
//
#import "CopyEnableLabel.h"
@implementation CopyEnableLabel
- (instancetype)initWithFrame:(CGRect)frame{
if (self == [super initWithFrame:frame]) {
[self initializationSetting];
}
return self;
}
//初始化設(shè)置,打開用戶交互功能,添加長按手勢
- (void)initializationSetting{
self.userInteractionEnabled = YES;
UILongPressGestureRecognizer *longGes = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressAction:)];
longGes.minimumPressDuration = 1;
[self addGestureRecognizer:longGes];
}
//長按彈出拷貝選項(xiàng)
- (void)longPressAction:(UILongPressGestureRecognizer *)longGes{
[self becomeFirstResponder];
UIMenuItem *copyItem = [[UIMenuItem alloc]initWithTitle:@"拷貝" action:@selector(copyText:)];
[[UIMenuController sharedMenuController]setMenuItems:[NSArray arrayWithObjects:copyItem,nil]];
[[UIMenuController sharedMenuController]setTargetRect:self.frame inView:self.superview];
[[UIMenuController sharedMenuController]setMenuVisible:YES animated:YES];
}
// 開啟label響應(yīng)事件的功能
- (BOOL)canBecomeFirstResponder{
return YES;
}
//控制響應(yīng)事件的方法
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
return action == @selector(copyText:);
}
//修改粘貼板內(nèi)容
- (void)copyText:(id)sender{
[UIPasteboard generalPasteboard].string = self.text;
}
@end
最后出來的效果:
WeChate1244fa0ff852164393ffec1441d7445.png