鍵盤會遮住輸入框,是每個表單頁都會遇到的問題。處理方式有兩種:一是把整個 ScrollView 的 contentInset 加大,二是像本文這樣直接監聽鍵盤通知、取得高度後自行位移。後者控制力更強,也更容易做出自訂動畫。
在 viewDidLoad 中監聽「即將顯示」與「即將隱藏」兩個事件。刻意選 Will 系列而非 Did,是為了能掌握動畫時序,讓版面位移與鍵盤出現同步。
- (void)viewDidLoad {
[super viewDidLoad];
// 鍵盤即將出現或改變時
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardWillShowNotification
object:nil];
// 鍵盤即將退出時
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
高度並不是寫死的值,它會隨鍵盤類型(中文、九宮格、表情符號、內建 Predictive Bar)而變,因此必須從通知的 userInfo 中取出:
- (void)keyboardDidShow:(NSNotification *)notification {
NSDictionary *userInfo = [notification userInfo];
CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
_keyBoardHeight = keyboardSize.height;
[self changeViewYByShow];
}
- (void)keyboardDidHide:(NSNotification *)notification {
_keyBoardHeight = 0;
[self changeViewYByHide];
}
#pragma mark - private methods
- (void)changeViewYByShow {
[UIView animateWithDuration:0.2 animations:^{
CGRect rect = self.view.frame;
rect.origin.y -= self.keyBoardHeight;
self.view.frame = rect;
}];
}
- (void)changeViewYByHide {
CGRect rect = self.view.frame;
rect.origin.y = 64;
self.view.frame = rect;
}
在 dealloc 或 viewDidDisappear 中移除通知註冊,否則頁面釋放後收到通知會直接 crash:
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
上面這段能跑,但有三個地方值得改進。
第一,位移量不該直接扣整個鍵盤高度。若輸入框本來就在畫面上半部,鍵盤根本遮不到它,硬扣只會把畫面推到不該有的位置。正確作法是先算出輸入框轉換到 window 座標後的 frame,判斷它是否真的會被鍵盤重疊,只補上差額。
第二,動畫應該跟隨鍵盤本身。userInfo 裡除了 UIKeyboardFrameBeginUserInfoKey,還有 UIKeyboardFrameEndUserInfoKey、UIKeyboardAnimationDurationUserInfoKey 與 UIKeyboardAnimationCurveUserInfoKey。把後兩者取出來套進 animateWithDuration:delay:options:animations:completion:,版面位移才會與鍵盤完全同步,而不是各跑各的。
第三,UIKeyboardWillChangeFrameNotification 涵蓋了鍵盤「切換高度」的情況(例如從英文鍵盤切到表情符號鍵盤),只監聽 WillShow 會漏掉這類變化。
若只是簡單表單,其實把內容放進 UIScrollView,實作 keyboardWillShow 時調整 contentInset.bottom 與 scrollIndicatorInsets,再 scrollRectToVisible: 把輸入框捲進來,會比直接改 view.frame 更穩健,旋轉與分屏時也不容易出錯。