鍵盤彈出時會蓋住下方的輸入區域,這是新手幾乎都會遇到的問題。處理思路是:監聽鍵盤的通知,取得鍵盤高度與動畫時間,然後把輸入框往上推相同的距離,收合時再復原。
- (void)registerForKeyboardNotifications {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification
object:nil];
}
- (void)unregisterForKeyboardNotifications {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self registerForKeyboardNotifications];
_viewFrame = _inputDiaryView.frame; // 先記下原始位置
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[self unregisterForKeyboardNotifications];
}
在 viewWillAppear 先把輸入框的 frame 存起來是必要的,因為 keyboardWillBeHidden 時需要這個原始值才能準確復原。
- (void)keyboardWasShown:(NSNotification *)aNotification {
CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
NSTimeInterval animationDuration =
[[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView beginAnimations:@"TEXTVIEW_KEYBOARD" context:nil];
[UIView setAnimationDuration:animationDuration];
_inputDiaryView.frame = CGRectMake(0,
_viewFrame.origin.y - keyboardRect.size.height,
_viewFrame.size.width,
_viewFrame.size.height);
[UIView commitAnimations];
}
- (void)keyboardWillBeHidden:(NSNotification *)aNotification {
NSTimeInterval animationDuration =
[[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView beginAnimations:@"TEXTVIEW_KEYBOARD" context:nil];
[UIView setAnimationDuration:animationDuration];
_inputDiaryView.frame = _viewFrame;
[UIView commitAnimations];
}
其中 _viewFrame 是 UITextView 父控制項的 frame,_inputDiaryView 則是 UITextView 的父控制項本身。

第一,UIKeyboardWillShowNotification 與 DidShow 有時機差異。用 WillShow 搭配動畫能讓位移與鍵盤出現同步,視覺上更順;用 DidShow 則鍵盤已經完全出現才開始動,容易有一瞬間的閃跳。
第二,抽高度時建議直接用 UIKeyboardFrameEndUserInfoKey 的 frame 去減掉 view 的底邊,而不是簡單地減去整個鍵盤高度。因為鍵盤有可能是覆蓋式(例如內建的 QuickType 建議列),簡單相減會推出過多的距離。
第三,iOS 8 之後鍵盤高度會因切換輸入法而變,建議同時監聽 UIKeyboardWillChangeFrameNotification,並把「往上推多少」抽成一個獨立方法重複呼叫,避免鍵盤高度變動時版面沒有跟著調整。
第四,這裡用的是 beginAnimations 這套老寫法,新專案改用 [UIView animateWithDuration:animations:] 會更簡潔,也比較容易加上 completion 處理。