设置UILabel可复制

目前iOS上自带支持拷贝黏贴的控件主要是:UITextField,UITextView,UIWebView
然而在很多情况下我们也会遇到需要在某些显示Label中支持长按复制的功能,如果需要做到拷贝这一点,我们需要自定义一个继承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;
}

//初始化设置,打开用户交互功能,添加长按手势
- (void)initializationSetting{
    self.userInteractionEnabled = YES;
    UILongPressGestureRecognizer *longGes = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressAction:)];
    longGes.minimumPressDuration = 1;
    [self addGestureRecognizer:longGes];
}

//长按弹出拷贝选项
- (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响应事件的功能
- (BOOL)canBecomeFirstResponder{
    return YES;
}

//控制响应事件的方法
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    return action == @selector(copyText:);
}

//修改粘贴板内容
- (void)copyText:(id)sender{
    [UIPasteboard generalPasteboard].string = self.text;
}


@end

最后出来的效果:


设置UILabel可复制_第1张图片
WeChate1244fa0ff852164393ffec1441d7445.png

你可能感兴趣的:(设置UILabel可复制)