第一步
自定义UILabel
重写下面两个方法
//让label有资格成为第一响应者
- (BOOL)becomeFirstResponder
{
return YES;
}
//label能执行哪些操作(比如 拷贝 等)
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (action == @selector(copy:) || action == @selector(paste:) || action == @selector(cut:)) return YES;
return NO;
}
第二步
实现相应功能的方法
- (void)copy:(UIMenuController *)menu
{
//将自己的文字赋值到粘贴板
[self copy:menu];
//清空文字
self.text = nil;
}
- (void)paste:(UIMenuController *)menu
{
//将自己的文字赋值到粘贴板
UIPasteboard * board = [UIPasteboard generalPasteboard];
board.string = self.text;
}
- (void)cut:(UIMenuController *)menu
{
UIPasteboard * board = [UIPasteboard generalPasteboard];
self.text = board.string;
}
第三步
给UILabel添加手势
- (void)awakeFromNib
{
[self setup];
[super awakeFromNib];
}
- (instancetype)initWithFrame:(CGRect)frame
{
if (self == [super initWithFrame:frame]) {
[self setup];
}
return self;
}
- (void)setup
{
self.userInteractionEnabled = YES;
[self addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(labelClick)]];
}
显示menu
- (void)labelClick
{
//1.让label成为第一响应者(这里的self是UILabel)
[self becomeFirstResponder];
//2.显示menuController
UIMenuController * menu = [UIMenuController sharedMenuController];
// [menu setTargetRect:self.frame inView:self.superview];
[menu setTargetRect:self.bounds inView:self];
[menu setMenuVisible:YES animated:YES];
NSLog(@"%s",__func__);
}
OVER
如果你想自定义的话可以写下面方法(相应的实现方法需要再控制器里面实现不然用不了)
UIMenuController * menu = [UIMenuController sharedMenuController];
UIMenuItem * reply = [[UIMenuItem alloc]initWithTitle:@"回复" action:@selector(replay:)];
UIMenuItem * ding = [[UIMenuItem alloc]initWithTitle:@"顶" action:@selector(ding:)];
UIMenuItem * report = [[UIMenuItem alloc]initWithTitle:@"举报" action:@selector(report:)];
menu.menuItems = @[reply,ding,report];