前言
網(wǎng)上有很多種給label添加長(zhǎng)按復(fù)制功能的方法,而在 uilabel 上實(shí)現(xiàn)長(zhǎng)按復(fù)制,我用的是 uimenucontroller。在 uitextview、uitextfield 中,已經(jīng)自帶了這個(gè)東西,但是在 uilabel 上需要自定義。
鑒于有的朋友很少接觸 uimenucontroller,這里先介紹一些基本知識(shí)。
uimenucontroller 可以使用系統(tǒng)自帶的方法,也可以自定義。
系統(tǒng)默認(rèn)支持uitextfield、uitextview、uiwebview控件的uimenucontroller相關(guān)操作
更多uimenucontroller使用請(qǐng)參考這篇文章:http://www.ythuaji.com.cn/article/133807.html
常見的系統(tǒng)方法和使用
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); |
從字面意思就能看出,他們是剪切、復(fù)制、粘貼、選擇、全選、刪除。使用方法很簡(jiǎn)單。
1
2
3
4
5
6
|
// 比如我在一個(gè) uitextview 里,想增加全選和復(fù)制的方法 // 只要在自定義 uitextview 的時(shí)候加入這行代碼即可 - ( bool )canperformaction:(sel)action withsender:(id)sender { if (action == @selector(selectall:) || action == @selector(copy:)) return yes; return no; } |
細(xì)心的朋友可能會(huì)發(fā)現(xiàn),最后長(zhǎng)按出來的文字都是英文,我們改如何把他改成中文呢?如圖,在 project -> info -> localizations 中添加 chinese(simplified) 即可。
自定義方法和使用
回到主題,我們要在 uilabel 上加入長(zhǎng)按復(fù)制事件,但是他本身是不支持 uimenucontroller 的,所以接下來講講自定義方法。
自定義一個(gè) uilabel,設(shè)置label可以成為第一響應(yīng)者
1
2
3
|
- ( bool )canbecomefirstresponder { return yes; } |
設(shè)置長(zhǎng)按事件,在初始化的時(shí)候調(diào)用這個(gè)方法
1
2
3
4
5
|
- ( void )setup { /* 你可以在這里添加一些代碼,比如字體、居中、夜間模式等 */ self.userinteractionenabled = yes; [self addgesturerecognizer:[[uilongpressgesturerecognizer alloc]initwithtarget:self action:@selector(longpress)]]; } |
長(zhǎng)按事件,在里面新建 uimenucontroller
1
2
3
4
5
6
7
8
9
10
11
12
|
- ( void )longpress { // 設(shè)置label為第一響應(yīng)者 [self becomefirstresponder]; // 自定義 uimenucontroller uimenucontroller * menu = [uimenucontroller sharedmenucontroller]; uimenuitem * item1 = [[uimenuitem alloc]initwithtitle:@ "復(fù)制" action:@selector(copytext:)]; menu.menuitems = @[item1]; [menu settargetrect:self.bounds inview:self]; [menu setmenuvisible:yes animated:yes]; } |
設(shè)置label能夠執(zhí)行那些
1
2
3
4
5
6
7
|
- ( bool )canperformaction:(sel)action withsender:(id)sender { if (action == @selector(copytext:)) return yes; return no; } // 如果模仿上面的寫以下代碼,點(diǎn)擊后會(huì)導(dǎo)致程序崩潰 if (action == @selector(selectall:) || action == @selector(copy:)) return yes; |
方法的具體實(shí)現(xiàn)
1
2
3
4
5
6
7
8
|
- ( void )copytext:(uimenucontroller *)menu { // 沒有文字時(shí)結(jié)束方法 if (!self.text) return ; // 復(fù)制文字到剪切板 uipasteboard * paste = [uipasteboard generalpasteboard]; paste.string = self.text; } |
最終效果:
附上 demo ,自定義的 uilabel 可以直接拖走使用
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)服務(wù)器之家的支持。
原文鏈接:https://segmentfault.com/a/1190000011690580