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];
实现键盘显示和键盘隐藏方法
在键盘显示方法中获取键盘高度。并配置键盘视图位移【值得一提的是,该方法会在用户切换中英文输入法的时候也会运行。因此不必操心在切换到中文输入法时键盘有多出一部分的问题】。
- (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不被键盘盖住。


原文地址:https://www.cnblogs.com/zhchoutai/p/6781550.html