在iOS開發中,我們經常處理這樣的情況:
當鍵盤出現或者消失的時候,我們需要做一些相應的操作。比如鍵盤上面的工具條的位置變化等。
這里我們就假設有一個工具條在鍵盤的上面,我們要求當鍵盤出現的時候,工具條的位置向上移動始終在鍵盤的上面,當鍵盤消失的時候,工具條向下移動到屏幕的下面。
這時候,我們應該怎么處理呢?
是不是覺得思路很清晰了,那么開始吧。
1、給鍵盤設一個通知
/** * 給鍵盤的frame改變添加監聽 * @param keyBoardWillChangeFrame: 監聽方法 */[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];2、在鍵盤的通知監聽方法里面做需要的操作
- (void)keyboardWillChangeFrame:(NSNotification *)notification{ // 鍵盤顯示/隱藏完畢的frame CGRect frame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; // 修改底部約束 self.bottomSapce.constant = XMGScreenH - frame.origin.y; // 動畫時間 CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; // 動畫 [UIView animateWithDuration:duration animations:^{ [self.view layoutIfNeeded]; }];}上一段代碼解釋:
notification.userInfo:
self.toolbar.transform = CGAffineTransformMakeTranslation(0, -keyboardF.size.height);@PRoperty (readwrite, retain) UIView *inputView;最后,一定要記得在dealoc方法里釋放監聽
- (void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self];}有時候在同一個界面里面,可能有多個TextField輸入框,而點擊不同額輸入框,我們可能希望彈出的鍵盤擁有不同的工具條,這時候我們怎么辦呢?
//這里不貼圖了,比較簡單UIView *tool1 = [[[NSBundle mainBundle] loadNibNamed:@"ToolBar1" owner:nil options:nil] lastObject];UIView *tool2 = [[[NSBundle mainBundle] loadNibNamed:@"ToolBar2" owner:nil options:nil] lastObject];self.textField1.inputAccessoryView = tool1;self.textField2.inputAccessoryView = tool2;成為第一響應者(可以調出鍵盤)
- (BOOL)becomeFirstResponder;取消第一響應者
- (BOOL)resignFirstResponder;全部取消第一響應者
- (BOOL)endEditing:(BOOL)force; //使用這個使得view或者其所有的子視圖都取消第一響應者 (optionally force)新聞熱點
疑難解答