關於點選UIButton彈出鍵盤,並且鍵盤的上方還需新增UITextField或者UITextView的解決方法
阿新 • • 發佈:2019-02-04
最近在做一個專案的時候,有這樣一個需求,點選UIButton彈出鍵盤,鍵盤的上方還需新增一個輸入框(UITextField/UITextView),開始的想法是直接設定輸入框的
inputAccessoryView,設定後發現鍵盤根本就沒顯示出來.經過無數次的修改與查詢資料之後,終於大功告成。廢話不多說了,先上程式碼。
//建立輸入框檢視
- (void)createCommentsView { if (!commentsView) { commentsView = [[UIView alloc] initWithFrame:CGRectMake(0.0, SCREEN_HEIGHT - TAB_BAR_HEIGHT - 40.0, SCREEN_WIDTH, 40.0)]; commentsView.backgroundColor = [UIColor whiteColor]; commentText = [[UITextView alloc] initWithFrame:CGRectInset(commentsView.bounds, 5.0, 5.0)]; commentText.layer.borderColor = [COLORRGB(212.0, 212.0, 212.0) CGColor]; commentText.layer.borderWidth = 1.0; commentText.layer.cornerRadius = 2.0; commentText.layer.masksToBounds = YES; commentText.inputAccessoryView = commentsView; commentText.backgroundColor = [UIColor clearColor]; commentText.returnKeyType = UIReturnKeySend; commentText.delegate = self; commentText.font = [UIFont systemFontOfSize:15.0]; [commentsView addSubview:commentText]; } [self.view.window addSubview:commentsView];//新增到window上或者其他檢視也行,只要在檢視以外就好了 [commentText becomeFirstResponder];//讓textView成為第一響應者(第一次)這次鍵盤並未顯示出來,(個人覺得這裡主要是將commentsView設定為commentText的inputAccessoryView,然後再給一次焦點就能成功顯示) }
- (void)showCommentText {
[self createCommentsView];
[commentText becomeFirstResponder];//再次讓textView成為第一響應者(第二次)這次鍵盤才成功顯示
}
//button的點選事件
- (void)handleClickComment:(UIButton *) sender { //這裡是為了防止連續點選 sender.userInteractionEnabled = NO; [sender performSelector:@selector(setUserInteractionEnabled:) withObject:@YES afterDelay:1]; [self showCommentText]; }