鍵盤高度沒有一個現成的屬性可以直接讀,標準做法是監聽鍵盤的通知,從通知附帶的 userInfo 裡把 frame 取出來。以下是一段可直接使用的實作。
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidHide:)
name:UIKeyboardDidHideNotification
object:nil];
}
除了 Did 系列,還有 UIKeyboardWillShowNotification 與 UIKeyboardWillHideNotification。差別在於時機:Will 系列在動畫開始前觸發,適合搭配自訂動畫讓版面位移與鍵盤同步;Did 系列則在動畫結束後才觸發。若你希望畫面滑順地跟著鍵盤一起移動,應該用 Will 系列。
- (void)keyboardDidShow:(NSNotification *)notification {
NSDictionary *userInfo = [notification userInfo];
_keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
[self updateTextViewSize];
}
- (void)keyboardDidHide:(NSNotification *)notification {
_keyboardSize = CGSizeMake(0.0, 0.0);
[self updateTextViewSize];
}
userInfo 裡有兩個相關的 key:UIKeyboardFrameBeginUserInfoKey 與 UIKeyboardFrameEndUserInfoKey,分別代表動畫前後的 frame。取 Begin 適合「最終要留多少空間」的計算,取 End 則是動畫結束後的實際位置。
- (void)updateTextViewSize {
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
CGFloat keyboardHeight = UIInterfaceOrientationIsLandscape(orientation)
? _keyboardSize.width
: _keyboardSize.height;
_textView.frame = CGRectMake(0,
0,
self.view.frame.size.width,
self.view.frame.size.height - keyboardHeight);
}
這段程式裡最關鍵的一行是 landscape 時取 width。通知回傳的鍵盤 frame 是相對於「螢幕座標系」的,橫屏時鍵盤的寬度才是它在垂直方向佔掉的高度,直接取 height 會得到錯誤的數字。
记得移除觀察者。在 dealloc 或 viewDidDisappear 中呼叫 removeObserver:,避免通知持續送進已失效的物件。
鍵盤AssociatedKeys 與 InputAccessory 會改變高度。如果鍵盤上方掛了 accessory view,通知回傳的 frame 已經含入該區域,不需要另外再加一次。
更省事的做法是使用 IQKeyboardManager。它自動處理了 Tab 鍵切換輸入框、點擊空白處收起鍵盤、以及依當前 first responder 自動捲動等一連串瑣事,多數專案導入它比手寫可靠得多。
如果專案使用 Auto Layout,還有一個更優雅的路徑:不要直接改 frame,而是對底部約束的 constant 做動畫更新,讓 Auto Layout 自己處理重排,能避免 frame 計算與約束系統互相打架的問題。