當頁面上有靠下方的輸入框時,一旦彈出軟鍵盤,往往會把輸入框整個蓋住,使用者根本看不到自己打了什麼。這是新手常遇到的經典問題。本文示範透過 UITextFieldDelegate 監聽編輯狀態,在鍵盤出現時把視圖往上推開。
1)將輸入框的代理設為 self
在 xib 中把輸入框的 delegate 連到 File's Owner,或用程式碼設定:textField.delegate = self;
2)讓 ViewController 採用 UITextFieldDelegate 協議
在 ViewController.h 中宣告遵守 UITextFieldDelegate,然後在 .m 中實作以下方法即可。
#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);
}
// 觸摸 view 隱藏鍵盤
- (IBAction)View_TouchDown:(id)sender {
// 送出 resignFirstResponder
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}
核心思路是:在 textFieldDidBeginEditing: 中計算鍵盤會遮住多少,把整個視圖往上推;在 textFieldDidEndEditing: 中再把視圖歸位。搭配 textFieldShouldReturn: 收起鍵盤,以及一個空白處的點擊事件(View_TouchDown:)來主動關閉鍵盤,整體互動就順暢多了。若頁面元素較多,也可以改用 UIScrollView 搭配 keyboard notification 的方式來處理,思路大同小異。