UITextFieldui
UITextViewcode
UIWebVieworm
...開發
// 一、讓自定義的 UILabel 有資格成爲第一響應者 - (BOOL)canBecomeFirstResponder { return YES; } // 二、自定義的 UILabel 的 Menu 能執行哪些操做 - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { // cut:剪切 / copy:複製 / paste:粘貼 if (action == @selector(cut:) || action == @selector(copy:) || action == @selector(paste:)) { return YES; } return NO; } // 三、那這些方法怎麼實現呢 - (void)cut:(UIMenuController *)menu { // 先將本身的文字複製到粘貼板 [self copy:menu]; // 在清空文字 self.text = nil; } - (void)copy:(UIMenuController *)menu { // 將本身的文字複製到粘貼板 UIPasteboard *board = [UIPasteboard generalPasteboard]; board.string = self.text; } - (void)paste:(UIMenuController *)menu { // 將粘貼板的文字複製到本身身上 UIPasteboard *board = [UIPasteboard generalPasteboard]; self.text = board.string; } // 四、系統的 menuController 方法還有 selector: / selectAll: /delete: 等
- (void)labelClick { // 讓 自定義的label 成爲第一響應者 [self.label becomeFirstResponder]; // 建立 UIMenuController UIMenuController *menu = [UIMenuController sharedMenuController]; // 設置 UIMenuController 的顯示區域,targetRect 爲指向的矩形框,inView 爲以該 view 的左上角爲原點 [menu setTargetRect:self.view.bounds inView:self.view]; // 設置可見 [menu setMenuVisible:YES animated:YES]; }
// 一、讓自定義的 UILabel 有資格成爲第一響應者 - (BOOL)canBecomeFirstResponder { return YES; } // 二、自定義的 UILabel 的 Menu 能執行哪些操做 , 自定義返回 NO - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { return NO; }
外部控制器裏, 給 label 添加點擊手勢,在手勢方法裏get
- (void)labelClick { UIMenuController *menu = [UIMenuController sharedMenuController]; // 先處理以前的 if (menu.menuVisible) { [menu setMenuVisible:NO animated:YES]; } else { [self.label becomeFirstResponder]; // 建立自定義的 UIMenuItem UIMenuItem *item1 = [[UIMenuItem alloc]initWithTitle:@"zhang1" action:@selector(item1Click)]; UIMenuItem *item2 = [[UIMenuItem alloc]initWithTitle:@"zhang2" action:@selector(item2Click)]; // 設置 MenuItem [menu setMenuItems:@[item1, item2]]; [menu setTargetRect:self.view.bounds inView:self.view]; [menu setMenuVisible:YES animated:YES]; } } // 實現 UIMenuItem 對應的方法 - (void)item1Click { } - (void)item2Click { }
// 一、讓自定義的 cell 有資格成爲第一響應者 - (BOOL)canBecomeFirstResponder { return YES; } // 二、自定義的 cell 的 Menu 能執行哪些操做, 自定義返回 NO - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { return NO; }
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UIMenuController *menu = [UIMenuController sharedMenuController]; // 先處理以前的 if (menu.menuVisible) { [menu setMenuVisible:NO animated:YES]; } else { DIYCell *cell = [tableView cellForRowAtIndexPath:indexPath]; [cell becomeFirstResponder]; UIMenuItem *item1 = [[UIMenuItem alloc]initWithTitle:@"zhang1" action:@selector(item1Click)]; UIMenuItem *item2 = [[UIMenuItem alloc]initWithTitle:@"zhang2" action:@selector(item2Click)]; [menu setMenuItems:@[item1, item2]]; // 設置 menu 的指向的矩形框 CGRect rect = CGRectMake(0, cell.diy_height * 0.5, cell.diy_width, cell.diy_height * 0.5); [menu setTargetRect:rect inView:cell]; [menu setMenuVisible:YES animated:YES]; } }