iOS可以长按复制的label

  • Post author:
  • Post category:其他




可以长按复制的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



版权声明:本文为NLYNN原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。