IOS研究之多個UITextField的鍵盤處理
在IOS開發中使用UITextField時常需要考慮的問題就是鍵盤的處理。有時候,彈出的鍵盤會將UITextField地區覆蓋,影響使用者輸入。這個時候就要將視圖上移。這個時候我們需要考慮兩點:1,修改視圖座標的時機;2,上移的位移是多大。3,UITableView設定Section間距 不明白的可以看看。我根據自己實際操作的實現方法如下:1,擷取正在編輯的UITextField的指標定義一個全域的UITextField的指標UITextField *tempTextFiled;在UITextFieldDelegate代理方法-(void)textFieldDidBeginEditing:(UITextField *)textField中修正tempTextFiled的值為當前正在編輯的UITextField的地址。-(void)textFieldDidBeginEditing:(UITextField *)textField{ tempTextFiled = textField;}
2,配置鍵盤處理事件在- (void)viewDidLoad中實現鍵盤監聽:[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];實現鍵盤顯示和鍵盤隱藏方法在鍵盤顯示方法中擷取鍵盤高度,並配置鍵盤視圖位移【值得一提的是,該方法會在使用者切換中英文IME的時候也會執行,因此不必擔心在切換到中文IME時鍵盤有多出一部分的問題】。- (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;//鍵盤的高度
NSLog(@"textField superview].frame.origin.y = %f",[tempTextFiled superview].frame.origin.y);
NSLog(@"keyboardHeight = %f",keyboardHeight);
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);
frame.origin.y -= [tempTextFiled superview].frame.origin.y + keyboardHeight + REGISTERTABLE_CELL_HEGHIT +20 - [[UIScreen mainScreen] bounds].size.height + 44;//位移量=編輯框原點Y值+鍵盤高度+編輯框高度-螢幕高度
registerTableView.frame=frame;
}
} 然後實現鍵盤隱藏的處理:在UITextFieldDelegate代理方法-(void)textFieldDidEndEditing:(UITextField *)textFieldView或者- (void)keyboardWillHide:(NSNotification *)notification方法中實現視圖複位,如下代碼:CGRect frame = registerTableView.frame;frame.origin.y = 44;//修改視圖的原點Y座標即可。registerTableView.frame=frame;
3,移除監聽在-(void)viewDidDisappear:(BOOL)animated或者dealloc方法中移除監聽[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];這樣,無論我們的介面上有多少UITextField,只需要簡單的幾部就可以實現UITextField不被鍵盤蓋住。