当前位置:首页 > 通信资讯 > 正文

前言

网上有很多种给label添加长按复制功能的方法,而在 uilabel 上实现长按复制,我用的是 uimenucontroller。在 uitextview、uitextfield 中,已经自带了这个东西,但是在 uilabel 上需要自定义。

鉴于有的朋友很少接触 uimenucontroller,这里先介绍一些基本知识。

uimenucontroller 可以使用系统自带的方法,也可以自定义。

系统默认支持uitextfield、uitextview、uiwebview控件的uimenucontroller相关操作

更多uimenucontroller使用请参考这篇文章:http://www.zzvips.com/article/133807.html

常见的系统方法和使用

?
1 2 3 4 5 6 - (void)cut:(nullable id)sender ns_available_ios(3_0); - (void)copy:(nullable id)sender ns_available_ios(3_0); - (void)paste:(nullable id)sender ns_available_ios(3_0); - (void)select:(nullable id)sender ns_available_ios(3_0); - (void)selectall:(nullable id)sender ns_available_ios(3_0); - (void)delete:(nullable id)sender ns_available_ios(3_2);

从字面意思就能看出,他们是剪切、复制、粘贴、选择、全选、删除。使用方法很简单。

?
1 2 3 4 5 6 // 比如我在一个 uitextview 里,想增加全选和复制的方法 // 只要在自定义 uitextview 的时候加入这行代码即可 - (bool)canperformaction:(sel)action withsender:(id)sender { if(action == @selector(selectall:) || action == @selector(copy:)) return yes; return no; }

细心的朋友可能会发现,最后长按出来的文字都是英文,我们改如何把他改成中文呢?如图,在 project -> info -> localizations 中添加 chinese(simplified) 即可。

ios中uilabel实现长按复制功能实例代码(ios中uilabel实现长按复制功能实例代码)

自定义方法和使用

回到主题,我们要在 uilabel 上加入长按复制事件,但是他本身是不支持 uimenucontroller 的,所以接下来讲讲自定义方法。

自定义一个 uilabel,设置label可以成为第一响应者

?
1 2 3 - (bool)canbecomefirstresponder { return yes; }

设置长按事件,在初始化的时候调用这个方法

?
1 2 3 4 5 - (void)setup { /* 你可以在这里添加一些代码,比如字体、居中、夜间模式等 */ self.userinteractionenabled = yes; [self addgesturerecognizer:[[uilongpressgesturerecognizer alloc]initwithtarget:self action:@selector(longpress)]]; }

长按事件,在里面新建 uimenucontroller

?
1 2 3 4 5 6 7 8 9 10 11 12 - (void)longpress { // 设置label为第一响应者 [self becomefirstresponder]; // 自定义 uimenucontroller uimenucontroller * menu = [uimenucontroller sharedmenucontroller]; uimenuitem * item1 = [[uimenuitem alloc]initwithtitle:@"复制" action:@selector(copytext:)]; menu.menuitems = @[item1]; [menu settargetrect:self.bounds inview:self]; [menu setmenuvisible:yes animated:yes]; }

设置label能够执行那些

?
1 2 3 4 5 6 7 - (bool)canperformaction:(sel)action withsender:(id)sender { if(action == @selector(copytext:)) return yes; return no; } // 如果模仿上面的写以下代码,点击后会导致程序崩溃 if(action == @selector(selectall:) || action == @selector(copy:)) return yes;

方法的具体实现

?
1 2 3 4 5 6 7 8 - (void)copytext:(uimenucontroller *)menu { // 没有文字时结束方法 if (!self.text) return; // 复制文字到剪切板 uipasteboard * paste = [uipasteboard generalpasteboard]; paste.string = self.text; }

最终效果:

ios中uilabel实现长按复制功能实例代码(ios中uilabel实现长按复制功能实例代码)

附上 demo,自定义的 uilabel 可以直接拖走使用

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:https://segmentfault.com/a/1190000011690580

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。