在 UILabel 上實現長按複製,我用的是 UIMenuController。在 UITextView、UITextField 中,已經自帶了這個東西,可是在 UILabel 上須要自定義。鑑於有的朋友不多接觸 UIMenuController,這裏先介紹一些基本知識。git
UIMenuController 能夠使用系統自帶的方法,也能夠自定義。github
- (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);
從字面意思就能看出,他們是剪切、複製、粘貼、選擇、全選、刪除。使用方法很簡單。字體
// 好比我在一個 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) 便可。spa
回到主題,咱們要在 UILabel 上加入長按複製事件,可是他自己是不支持 UIMenuController 的,因此接下來說講自定義方法。code
自定義一個 UILabel,設置label能夠成爲第一響應者
- (BOOL)canBecomeFirstResponder { return YES; }
設置長按事件,在初始化的時候調用這個方法
- (void)setUp { /* 你能夠在這裏添加一些代碼,好比字體、居中、夜間模式等 */ self.userInteractionEnabled = YES; [self addGestureRecognizer:[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress)]]; }
長按事件,在裏面新建 UIMenuController
- (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可以執行那些
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender { if(action == @selector(copyText:)) return YES; return NO; } // 若是模仿上面的寫如下代碼,點擊後會致使程序崩潰 if(action == @selector(selectAll:) || action == @selector(copy:)) return YES;
方法的具體實現
- (void)copyText:(UIMenuController *)menu { // 沒有文字時結束方法 if (!self.text) return; // 複製文字到剪切板 UIPasteboard * paste = [UIPasteboard generalPasteboard]; paste.string = self.text; }
最終效果:orm
附上 DEMO,自定義的 UILabel 能夠直接拖走使用事件