设置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

最后出来的效果:


WeChate1244fa0ff852164393ffec1441d7445.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容