要想在label中使用 必须是继承于label的分类
//
// MYlabel.m
// MenuController
//
// Created by 张明 on 16/3/8.
// Copyright © 2016年 张明. All rights reserved.
//
#import "MYlabel.h"
@implementation MYlabel
- (void)awakeFromNib
{
[self setup];
}
- (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)]];
}
/*
让label有资格成为第一响应者
*/
- (BOOL)canBecomeFirstResponder
{
return YES;
}
- (void)labelClick
{
//1.label要成为第一响应者(作用是:告诉UIMenuController支持哪些操作,这些操作如何处理)
[self becomeFirstResponder];
//2.显示MenuController
UIMenuController *menu = [UIMenuController sharedMenuController];
//targetRect :MenuController需要指向的矩形框
//targetview:targetrect会以targetview的左上角为坐标原点
[menu setTargetRect:self.bounds inView:self];
[menu setMenuVisible:YES animated:YES];
}
/*
label能执行哪些操作(比如copy.paste 等等)
@return YES:支持这种操作
*/
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (action == @selector(cut:) || action == @selector(copy:) || action == @selector(paste:)) return YES;
return NO;
}
- (void)copy:(id)sender
{
//将自己的文字赋值到粘贴板
UIPasteboard *board = [UIPasteboard generalPasteboard];
board.string = self.text;
}
- (void)cut:(id)sender
{
//将自己的文字赋值到粘贴板
[self copy:sender];
//清空文字
self.text = nil;
}
- (void)paste:(id)sender
{
//将粘贴板的文字复制到自己身上
UIPasteboard *board = [UIPasteboard generalPasteboard];
self.text = board.string;
}
@end