在iOS開發中,咱們常常處理這樣的狀況:工具
當鍵盤出現或者消失的時候,咱們須要作一些相應的操做。好比鍵盤上面的工具條的位置變化等。動畫
這裏咱們就假設有一個工具條在鍵盤的上面,咱們要求當鍵盤出現的時候,工具條的位置向上移動始終在鍵盤的上面,當鍵盤消失的時候,工具條向下移動到屏幕的下面。code
這時候,咱們應該怎麼處理呢?orm
是否是以爲思路很清晰了,那麼開始吧。server
/** * 給鍵盤的frame改變添加監聽 * @param keyBoardWillChangeFrame: 監聽方法 */ [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
- (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:rem
self.toolbar.transform = CGAffineTransformMakeTranslation(0, -keyboardF.size.height);
@property (readwrite, retain) UIView *inputView;
最後,必定要記得在dealoc方法裏釋放監聽input
- (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; }
有時候在同一個界面裏面,可能有多個TextField輸入框,而點擊不一樣額輸入框,咱們可能但願彈出的鍵盤擁有不一樣的工具條,這時候咱們怎麼辦呢?animation
//這裏不貼圖了,比較簡單 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;
成爲第一響應者(能夠調出鍵盤)it
- (BOOL)becomeFirstResponder;
取消第一響應者
- (BOOL)resignFirstResponder;
所有取消第一響應者
- (BOOL)endEditing:(BOOL)force; //使用這個使得view或者其全部的子視圖都取消第一響應者 (optionally force)