當一個 view 上有多個 UITextField,而最下面那個會被鍵盤蓋住時,就必須在鍵盤彈出時把整個介面往上推。這裡的做法是給每個 TextField 設定 tag,用 tag 來判斷「是不是那個會被遮住的欄位」,只有它獲得焦點時才平移畫面。
UITextField *name = ...;
name.tag = 2;下面以 tag == 2 為例,只有這個情況才需要把畫面上移。
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
// 點觸 textField 內部、開始編輯時呼叫,此時 textField 成為 first responder
if (textField.tag == 2) {
NSTimeInterval animationDuration = 0.30f;
CGRect frame = self.view.frame;
frame.origin.y -= 216;
frame.size.height += 216;
self.view.frame = frame;
[UIView beginAnimations:@"ResizeView" context:nil];
[UIView setAnimationDuration:animationDuration];
self.view.frame = frame;
[UIView commitAnimations];
}
}- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
// 使用者按下 return,把焦點從 textField 移開,鍵盤就會消失
if (textField.tag == 2) {
NSTimeInterval animationDuration = 0.30f;
CGRect frame = self.view.frame;
frame.origin.y += 216;
frame.size.height -= 216;
self.view.frame = frame;
[UIView beginAnimations:@"ResizeView" context:nil];
[UIView setAnimationDuration:animationDuration];
self.view.frame = frame;
[UIView commitAnimations];
}
[textField resignFirstResponder];
return YES;
}位移量 216 是依鍵盤高度估算的經驗值,加上/減去之後再包成動畫,畫面就會平滑地上下滑動,而不是硬跳。
寫死 216 不可靠。不同裝置、不同鍵盤類型(一般鍵盤、九宮格、注音、emoji 鍵盤)的高度都不一樣,加上 iOS 7 之後還有 Predictive text 的建議列,硬編碼幾乎一定會在某些情境下露出破綻。正確做法是用 UIKeyboardWillShowNotification 通知,從 userInfo 中取出 UIKeyboardFrameEndUserInfoKey 拿到真實的鍵盤高度。
只處理了 return 鍵。如果使用者直接點畫面別處或使用鍵盤上的「完成」以外的路徑收起鍵盤,view 不會復位。比較穩妥的是同時監聽 UIKeyboardWillHideNotification,在那裡統一復原。
如果這個 view 的元件數量不多,最省事的做法是把它放進 UIScrollView,然後在鍵盤彈出時調整 contentInset.bottom,讓系統自己處理捲動;或直接改用 Auto Layout,替最下方的約束加上 keyboardLayoutGuide(iOS 15+ 可用 keyboardLayoutGuide,早期則需自行計算)的錨點,讓版面自動跟著鍵盤伸縮,完全不需要手動算 frame。