在我們開發中,經常會遇到鍵盤遮擋著輸入框的情況,那么我們怎么去解決呢,如果動態的調整輸入框,使其顯示出來不被遮擋。
我們主要的思路是,如果鍵盤遮擋了輸入框,那么就像整個頁面向上移動一定的距離,使其顯現出來。
什么時候頁面才會向上移動,當
textfield的距離屏幕的最大Y值 + 鍵盤的高度 > 屏幕的高度
就需要上移了。上移的高度就是
textfield的距離屏幕最大Y值 + 鍵盤的高度 — 屏幕的高度
現在,我們利用通知得到鍵盤的高度,首先我們認識一些通知
//鍵盤將要出現
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//鍵盤已經出現
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
//鍵盤將要消失
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
//鍵盤已經消失
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
//鍵盤的frame將要改變
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
//鍵盤的frame改變完畢
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
當鍵盤出現、消失或者改變frame的時候,都會觸發通知
我們主要是利用鍵盤已經出現進行屏幕上移 和 鍵盤已經消失進行屏幕還原。(當然你也可以利用鍵盤將要出線和將要消失進行屏幕的移動)
鍵盤高度我們可以在通知方法中,利用
- (void)keyboardDidShow:(NSNotification *)info {
//獲取鍵盤高度,
CGFloat kbHeight = [[info.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
NSLog(@"鍵盤高度 %f",kbHeight);
}
獲得。
最后別忘了在界面消失的時候移除觀察者
//鍵盤將要出現
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
//鍵盤已經出現
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
//鍵盤將要消失
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
//鍵盤已經消失
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
//鍵盤的frame將要改變
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
//鍵盤的frame改變完畢
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidChangeFrameNotification object:nil];
效果如下
這里只是說了一下思路,具體的代碼見下方。里面有詳細的備注
Demo代碼地址:https://github.com/312179361/KeyBoardManager.git
聯系方式:QQ:3020495503
有建議和意見的歡迎騷擾,共同交流。請備注,“我在簡書上看到你的博客,一起交流吧”。