當輸入框位置偏下時,鍵盤彈出會把它擋住。最簡單的解法是監聽 UITextField 的編輯狀態,在開始編輯時把整個視圖往上推一段距離,編輯結束後再復位。
以下實作透過 textFieldDidBeginEditing: 與 textFieldDidEndEditing: 兩個 delegate 方法完成:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
CGRect frame = textField.frame;
// 鍵盤高度:iPhone 約 216pt,iPad 約 352pt
int offset = frame.origin.y + 70 - (self.view.frame.size.height - 216.0);
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:0.3f];
// 把視圖的 Y 座標上移 offset,騰出空間給鍵盤
if (offset > 0) {
self.view.frame = CGRectMake(0.0f, -offset,
self.view.frame.size.width,
self.view.frame.size.height);
}
[UIView commitAnimations];
}
// 編輯結束後,視圖回到原始位置
- (void)textFieldDidEndEditing:(UITextField *)textField {
self.view.frame = CGRectMake(0, 0,
self.view.frame.size.width,
self.view.frame.size.height);
}
beginAnimations 寫法,新專案建議改用 [UIView animateWithDuration:animations:],語意更清楚。UIKeyboardWillShowNotification,直接從通知的 userInfo 中取出鍵盤實際高度。