iOS中UILabel实现长按复制功能实例代码

2025-05-29 0 38

前言

网上有很多种给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实现长按复制功能实例代码

自定义方法和使用

回到主题,我们要在 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实现长按复制功能实例代码

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

总结

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 iOS中UILabel实现长按复制功能实例代码 https://www.kuaiidc.com/89405.html

相关文章

发表评论
暂无评论