前言
網上有很多種給label添加長按復制功能的方法,而在 uilabel 上實現長按復制,我用的是 uimenucontroller。在 uitextview、uitextfield 中,已經自帶了這個東西,但是在 uilabel 上需要自定義。
鑒于有的朋友很少接觸 uimenucontroller,這里先介紹一些基本知識。
uimenucontroller 可以使用系統自帶的方法,也可以自定義。
系統默認支持uitextfield、uitextview、uiwebview控件的uimenucontroller相關操作
更多uimenucontroller使用請參考這篇文章:http://www.jfrwli.cn/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) 即可。
自定義方法和使用
回到主題,我們要在 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; } |
最終效果:
附上 demo ,自定義的 uilabel 可以直接拖走使用
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://segmentfault.com/a/1190000011690580