畫面下方的輸入框一旦獲得焦點,實體鍵盤就會從底部滑出把它蓋住,使用者看不到自己打了什麼。解法是讓整個視圖在鍵盤出現時向上挪一些空間,輸入結束後再歸位。
1. 設定代理:在 storyboard/xib 中把輸入框的 delegate 連到 File's Owner,或用程式碼指定 textField.delegate = self;。
2. 宣告協定:讓 ViewController 實作 UITextFieldDelegate。
3. 實作三個方法:
#pragma mark - UITextField Delegate
// 開始編輯:把視圖往上推
- (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];
// Y 座標上移 offset,為鍵盤騰出空間
if (offset > 0) {
self.view.frame = CGRectMake(0.0f,
-offset,
self.view.frame.size.width,
self.view.frame.size.height);
}
[UIView commitAnimations];
}
// 按下 Return:收起鍵盤
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
// 編輯結束:視圖復原
- (void)textFieldDidEndEditing:(UITextField *)textField {
self.view.frame = CGRectMake(0, 0,
self.view.frame.size.width,
self.view.frame.size.height);
}
4. 點擊空白處收起鍵盤:
- (IBAction)View_TouchDown:(id)sender {
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder)
to:nil
from:nil
forEvent:nil];
}
上面這套寫法簡單直觀,但硬編碼了鍵盤高度 216,在橫屏、不同機型或啟用了第三方鍵盤時就會失準。更穩健的做法是監聽 UIKeyboardWillShowNotification 與 UIKeyboardWillHideNotification,直接從通知的 userInfo 中取出鍵盤實際的 frame 與動畫曲線,再據此計算位移量。這樣不但能拿到正確高度,也能讓視圖位移與鍵盤動畫完全同步,視覺上更自然。
另一個常見的補強是:位移量不要寫死 100,而是依「輸入框底端與鍵盤頂端的重疊距離」來算,這樣一屏中同時有多個輸入框時,每個都能被正確露出來。