在 iOS 開發中使用 UITextField 時,鍵盤的處理是常見的問題。當弹出的鍵盤會遮擋住輸入框、影響使用者輸入時,就需要將視圖上移。這裡需要考慮兩點:修改視圖座標的時機,以及上移的偏移量。
先定義一個全域的 UITextField 指標,並在 textFieldDidBeginEditing 代理方法中,將它指向當前正在編輯的文本框:
UITextField *tempTextFiled;
- (void)textFieldDidBeginEditing:(UITextField *)textField {
tempTextFiled = textField;
}在 viewDidLoad 中註冊鍵盤的通知監聽:
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}在鍵盤顯示方法中取得鍵盤高度,並據此調整視圖位移。值得注意的是,該方法在使用者切換中英文輸入法時也會執行,因此不必擔心切換輸入法時鍵盤高度變化的問題:
- (void)keyboardWillShow:(NSNotification *)notification {
NSDictionary *info = [notification userInfo];
NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [self.view convertRect:[aValue CGRectValue] fromView:nil];
double keyboardHeight = keyboardRect.size.height; // 鍵盤的高度
if (([tempTextFiled superview].frame.origin.y + keyboardHeight + REGISTERTABLE_CELL_HEGHIT) >= ([[UIScreen mainScreen] bounds].size.height - 44)) {
// 此時編輯框被鍵盤蓋住,則對視圖做對應的位移
CGRect frame = CGRectMake(0, 44, 320, [[UIScreen mainScreen] bounds].size.height - 45);
// 偏移量 = 編輯框原點Y + 鍵盤高度 + 編輯框高度 - 屏幕高度
frame.origin.y -= [tempTextFiled superview].frame.origin.y + keyboardHeight + REGISTERTABLE_CELL_HEGHIT + 20 - [[UIScreen mainScreen] bounds].size.height + 44;
registerTableView.frame = frame;
}
}接著實現鍵盤隱藏時的視圖復位,可在 textFieldDidEndEditing 或 keyboardWillHide 方法中將視圖原點 Y 坐標還原:
CGRect frame = registerTableView.frame;
frame.origin.y = 44; // 修改視圖的原點 Y 坐標即可
registerTableView.frame = frame;在 viewDidDisappear 或 dealloc 方法中移除通知監聽,避免記憶體洩漏:
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];透過以上幾個步驟,無論界面上有多少個 UITextField,都能簡單地實現「輸入框不被鍵盤遮擋」的效果。