iOS 封装一个带复制功能的UILabel

一、在iOS中下面三个控件,自身就有复制-粘贴的功能:
1、UITextView
2、UITextField
3、UIWebView
在iOS8 之后, 我们发现UILabel不在为我们提供长按弹出复制等操作了, 我们来继承UILabel自己写一个带复制功能的UILabel

二、废话少说,直接撸代码

//
//  CopyLabel.m
//  Block学习二次学习01
//
//  Created by XianCheng Wang on 2018/8/4.
//  Copyright © 2018年 XianCheng Wang. All rights reserved.
//

#import "CopyLabel.h"
@implementation CopyLabel
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self pressAction];
    }
    return self;
}
// 初始化设置
- (void)pressAction {
    self.userInteractionEnabled = YES;
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
    longPress.minimumPressDuration = 0.25;
    [self addGestureRecognizer:longPress];
}

// 使label能够成为响应事件
- (BOOL)canBecomeFirstResponder {
    
    return YES;
}

// 自定义方法时才显示对就选项菜单,即屏蔽系统选项菜单
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(customCopy:)){
        
        return YES;
    }
    return NO;
}

// 父类视图
-(void)addSuperView{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeCopyLabel)];
    tap.numberOfTapsRequired = 1;
    [self.superview addGestureRecognizer:tap];
    self.alpha = kAlpha;
}
-(void)removeCopyLabel{
    self.alpha = 1.0;
}

- (void)customCopy:(id)sender {
    [self removeCopyLabel];
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = self.text;
}
- (void)longPressAction:(UIGestureRecognizer *)recognizer {
    // 父类视图
    [self addSuperView];
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        [self becomeFirstResponder];
        UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"拷贝" action:@selector(customCopy:)];
        UIMenuController *menuController = [UIMenuController sharedMenuController];
        menuController.menuItems = [NSArray arrayWithObjects:copyItem, nil];
        [menuController setTargetRect:self.frame inView:self.superview];
        [menuController setMenuVisible:YES animated:YES];
    }
}
@end

三、废话少说,直接看效果

- (void)viewDidLoad {
   [super viewDidLoad];
   self.navigationItem.title = @"CopyLabel";
   CopyLabel *copy = [[CopyLabel alloc] initWithFrame:CGRectMake(50,44, [UIScreen mainScreen].bounds.size.width - 100,35)];
   copy.text = @"清明时节雨纷纷,路上行人欲断魂。";
   copy.textColor = [UIColor yellowColor];
   copy.backgroundColor = [UIColor darkGrayColor];
   copy.textAlignment = NSTextAlignmentCenter;
   copy.font = [UIFont boldSystemFontOfSize:14];
   [self.view addSubview:copy];
}
copyLabel.gif

四、github地址:https://github.com/gitwangxiancheng/CopyLabel.git

五、是不是很心动,赶快试试吧❤️

你可能感兴趣的:(iOS 封装一个带复制功能的UILabel)