iOS如何封装带复制功能的UILabel示例代码

2020-01-21 07:08:36刘景俊

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


#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)customCopy:(id)sender {
 UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
 pasteboard.string = self.text;
}
- (void)longPressAction:(UIGestureRecognizer *)recognizer {
 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];
 CopyLabel *copy = [[CopyLabel alloc] initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width,50)];
 copy.text = @"清明时节雨纷纷,路上行人欲断魂。";
 copy.textAlignment = NSTextAlignmentCenter;
 copy.backgroundColor = [UIColor yellowColor];
 copy.textColor = [UIColor redColor];
 copy.font = [UIFont boldSystemFontOfSize:16];
 [self.view addSubview:copy];
}

iOS,封装,UILabel,代码

五、github地址:

https://www.easck.com/p>