最近因为想在UILabel中实现类UITextView的长按复制的功能,找到了UIMenuController,可以实现,但最终还是达不到像UITextView那样任意选择的功能,最终用UITextView代替UILaebl显示,在这里记录下UIMenuController的简单实现,并附件上Demo,先上图
关于UILable长按事件有个注意的地方,就是要先设置UILabel的
[self.labelsetUserInteractionEnabled:YES];//默认不接收任何事件
想要显示UIMenuViewController ,如下即可
- (void)showMenuViewController:(UIView*)showInView
{
UIMenuItem *flag = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(flag:)];
UIMenuItem *approve = [[UIMenuItem alloc] initWithTitle:@"Approve" action:@selector(approve:)];
UIMenuItem *deny = [[UIMenuItem alloc] initWithTitle:@"Deny" action:@selector(deny:)];
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setMenuItems:[NSArray arrayWithObjects:flag, approve, deny, nil]];
[menu setTargetRect:showInView.frame inView:showInView.superview];
[menu setMenuVisible:YES animated:YES];
}
而关于复制,用到了系统的复制面板UIPasteboard,只需设置UIPasteboard.string = string,即可以其他地方出现粘贴出string
UIPasteboard *gpBoard = [UIPasteboard generalPasteboard];//获取系统的UIPasteboard
[gpBoard setString:@"复制文字"];
自己也可以自定义UIPasteboard,详细自己找一下~_~;
demo下载地址: http://download.youkuaiyun.com/download/cjsen/4874724