做 iOS 一定會遇到這個問題:使用者點了文字輸入框,鍵盤彈出來,卻正好蓋住剛剛點擊的位置。
解法分三步。
@interface SignupViewController : UIViewController <UITextFieldDelegate>
選中文字框,在 Connections Inspector 中把 delegate 連到 controller。若你的介面完全以程式碼建立,則改為設定 textField.delegate = self;。
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
// 按下 return 時讓出焦點,鍵盤隨之收起,並把視圖還原
NSTimeInterval animationDuration = 0.30f;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
CGRect rect = CGRectMake(0.0f, 0.0f,
self.view.frame.size.width,
self.view.frame.size.height);
self.view.frame = rect;
[UIView commitAnimations];
[textField resignFirstResponder];
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
CGRect frame = textField.frame;
// 鍵盤高度約 216,推算出需要上移的距離
int offset = frame.origin.y + 32 - (self.view.frame.size.height - 216.0);
NSTimeInterval animationDuration = 0.30f;
[UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
[UIView setAnimationDuration:animationDuration];
float width = self.view.frame.size.width;
float height = self.view.frame.size.height;
if (offset > 0) {
CGRect rect = CGRectMake(0.0f, -offset, width, height);
self.view.frame = rect;
}
[UIView commitAnimations];
}
邏輯是:開始編輯時算出「輸入框底部超出可用區域多少」,把整個 view 往上推這麼多;結束編輯時歸零。offset 只有大於 0 才需要移動,避免往下推出現空白。
這套做法有兩個明顯限制,實務上建議改用更穩健的方案。
第一,216 是舊 iPhone 的鍵盤高度。加上上方 accessory bar、第三方鍵盤、不同語言鍵盤,以及後來放大的螢幕尺寸,寫死高度幾乎必然出錯。取而代之的做法是監聽 UIKeyboardWillChangeFrameNotification,直接從 userInfo 中讀取 UIKeyboardFrameEndUserInfoKey,用真實的鍵盤 frame 來計算。
第二,直接改 self.view.frame 會與 Auto Layout 打架,也可能影響其他子視圖。比較好的選擇是把需要上移的內容包在一個 UIScrollView 裡,鍵盤彈出時調整 contentInset,系統自帶的 scrollView 就能處理回彈與滾動,互動也自然得多。