問題:當UITextField輸入會彈出鍵盤,可以通過通知來監聽鍵盤的顯示或者隱藏獲取到鍵盤的高度。當切換鍵盤的輸入方法,就會改變鍵盤的高度,從而導致UIKeyboardWillShowNotification 鍵盤通知 被觸發了兩次或者多次;導致視圖不止一次網上移動,從而導致UI界面顯示不正常!
1. 當輸入文本框添加到不可滾動的View上
在viewDidLoad方法中監聽鍵盤的彈出和隱藏
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
實現通知方法
####完整正確的寫法
-(void) keyboardWillShow:(NSNotification *)notiInfo{
CGRect keyBoardRect=[notiInfo.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGRect selfViewFrame = self.view.frame;
selfViewFrame = CGRectMake(0, -keyBoardRect.size.height, self.view.frame.size.width, self.view.frame.size.height);
self.view.frame = selfViewFrame;
}
-(void) keyboardWillHide:(NSNotification *)notiInfo{
CGRect selfViewFrame = self.view.frame;
selfViewFrame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
self.view.frame = selfViewFrame;
}
### 錯誤原因
-(void) keyboardWillShow:(NSNotification *)notiInfo{
CGRect keyBoardRect=[notiInfo.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGRect selfViewFrame = self.view.frame;
## 最重要的就是不能執行像下面這句直接改變origin.y
selfViewFrame.origin.y = selfViewFrame.origin.y - keyBoardRect.size.height;(錯誤原因,重復的?坐標)
self.view.frame = selfViewFrame;
}
記得在視圖控制器銷毀的時候移除通知
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
2. 當文本框添加到滾動視圖上時,比如tableViewCell上面添加輸入框,點擊彈出鍵盤輸入內容。
:通知的實現方法可以改變滾動的內邊距,達到輸入不被鍵盤遮擋
-(void) keyboardWillShow:(NSNotification *)notiInfo{
CGRect keyBoardRect=[notiInfo.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
table.contentInset = UIEdgeInsetsMake(0, 0, keyBoardRect.size.height, 0);
}
-(void) keyboardWillHide:(NSNotification *)notiInfo{
table.contentInset = UIEdgeInsetsZero;
}
3.注冊或者登錄
- (void)isOldKeyBoardShow:(NSNotification *)notification {
NSDictionary *info = [notification userInfo];
NSValue *value = info[UIKeyboardFrameEndUserInfoKey];
CGPoint keyboard = [value CGRectValue].origin;
CGSize keyboardS = [value CGRectValue].size;
if (keyboard.y< screenH)
{//顯示鍵盤
loginView.center = CGPointMake(self.view.center.x, self.view.center.y- (keyboardS.height/2));
}else{
loginView.center = CGPointMake(self.view.center.x, self.view.center.y);
}
registerView.center = self.view.center;
}
4.問題:在使用 IQKeyboardManager 方法庫的時候遇到的bug,鍵盤彈出,不僅使window 視圖偏移鍵盤的高度,而且還導致導航欄也偏移出可視界面,從而破環了導航欄,導致整個app 界面出現問題!如下圖:
contentOffset改變
偏移量改變導致刷新視圖一直顯示
解決:不使用 IQKeyboardManager 三方庫,直接注銷,神奇的是問題依然存在。必須把三方庫移除工程,鍵盤的彈出才最終正常!