iOS可以长按复制的label

可以长按复制的label, 带有高亮显示

先看效果

在这里插入图片描述

思路

新建NYLCopyLabel继承自UILabel, 然后添加长按手势, 把text赋值给粘贴板, 当长按的label时候, label的背景显示高亮状态, 当复制按钮消失, 高亮取消. (利用UIMenuControllerWillHideMenuNotification的通知监听复制按钮消失)

使用方法

NYLCopyLabel *label = [NYLCopyLabel new];
[self.view addSubview:label];

封装的NYLCopyLabel类

NYLCopyLabel.m

//
//  NYLCopyLabel.m
//  GoodDoctorForDoctor
//
//  Created by nyl on 2019/7/17.
//

#import "NYLCopyLabel.h"

@interface NYLCopyLabel()

@property (nonatomic, strong) UIPasteboard *pasteboard;

@end

@implementation NYLCopyLabel

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.pasteboard = [UIPasteboard generalPasteboard];
        [self addLongPressGes];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuHideMenuNotification) name:UIMenuControllerWillHideMenuNotification object:nil];
    }
    return self;
}


- (void)addLongPressGes {
    self.userInteractionEnabled = YES;
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(actionLongPregressGes:)];
    [self addGestureRecognizer:longPress];
}

- (void)actionLongPregressGes:(UILongPressGestureRecognizer *)ges {
    // 防止长按之后连续触发该事件
    if (ges.state == UIGestureRecognizerStateBegan) {
        [self becomeFirstResponder];
        UIMenuController *menuCtrl = [UIMenuController sharedMenuController];
        [menuCtrl setTargetRect:self.frame inView:self.superview];
        [menuCtrl setMenuVisible:YES animated:YES];
        self.backgroundColor = [UIColor blueColor]; // 这个颜色值比较好看 #b2d7ff
    }
}


- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(copy:)) {
        return YES;
    }
    return NO;
}

- (void)copy:(id)sender {
    self.pasteboard.string = self.text;
}

- (void)menuHideMenuNotification {
    self.backgroundColor = nil;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIMenuControllerWillHideMenuNotification object:nil];
}

@end

NYLCopyLabel.h

//
//  NYLCopyLabel.h
//  GoodDoctorForDoctor
//
//  Created by nyl on 2019/7/17.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface NYLCopyLabel : UILabel

@end

NS_ASSUME_NONNULL_END

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值