先看效果:
在看代码:
//
// LYCopyLabel.m
// Null
//
// Created by liyang on 17/8/16.
// Copyright © 2017年 liyang. All rights reserved.
//
#import "LYCopyLabel.h"
@implementation LYCopyLabel
//指定LYCopyLabel可以成为第一响应者,配合UIMenuController使用
- (BOOL)canBecomeFirstResponder {
return YES;
}
//指定该LYCopyLabel可以响应的方法,系统提供了好多方法,我们只用粘贴复制
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
if (action == @selector(copyS:)) {
return YES;
}
if (action == @selector(pasteS:)) {
return YES;
}
return NO;
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self attachTapHandler];
}
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
[self attachTapHandler];
}
-(void)attachTapHandler {
self.userInteractionEnabled = YES;
UILongPressGestureRecognizer *touch = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[self addGestureRecognizer:touch];
}
-(void)handleTap:(UIGestureRecognizer*)recognizer {
if (recognizer.state == UIGestureRecognizerStateBegan) {
[self becomeFirstResponder];
UIMenuItem *copyLink = [[UIMenuItem alloc] initWithTitle:@"复制"
action:@selector(copyS:)];
UIMenuItem *pasteLink = [[UIMenuItem alloc] initWithTitle:@"粘贴"
action:@selector(pasteS:)];
UIMenuController *men = [UIMenuController sharedMenuController];
men.menuItems = @[copyLink,pasteLink];
men.arrowDirection = UIMenuControllerArrowDown;
[men setTargetRect:self.frame inView:self.superview];
[men setMenuVisible:YES animated:YES];
}
}
#pragma mark - 自定义事件
- (void)copyS:(id)sender {
UIPasteboard *pboard = [UIPasteboard generalPasteboard];
pboard.string = self.text;
}
- (void)pasteS:(id)sender{
UIPasteboard *pboard = [UIPasteboard generalPasteboard];
self.text = pboard.string;
}
@end
使用的时候用LYCopyLabel技能实现复制功能和粘贴功能