美文网首页
iOS开发 多个textfield简单键盘处理

iOS开发 多个textfield简单键盘处理

作者: 流浪的诗意 | 来源:发表于2016-12-20 14:57 被阅读0次

    iOS开发以及好多年了,但是对于键盘处理从未认真的想一个简单的办法来处理,网上有大把的方法,有些写的并不是那么详细,实际使用起来会出各种幺蛾子,现在找到一个简单的模式,把这些代码考进textField所在的ViewController即可,因为时间关系,只做了textField的简单归纳,当然对于textView也是有效的,废话不多说,开始吧:

    1,当然是要注册键盘的通知方法

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWillChange:)name:UIKeyboardWillChangeFrameNotificationobject:nil];

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotificationobject:nil];

    2,不要忘了取消注册通知,否则你会发现很蛋疼的,键盘会错乱

    - (void)dealloc{

    [[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIKeyboardWillChangeFrameNotificationobject:nil];

    [[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIKeyboardWillHideNotificationobject:nil];

    }

    3关键的来了,通知对应的方法

    3.1键盘弹起时,将被遮挡区域露出来,我们唯一需要做的一件事就是将当前控制器内的所有textField放进数组

    - (void)keyboardWillChange:(NSNotification*) notification{

    //获取键盘通知信息

    NSDictionary*info = [notificationuserInfo];

    //获取键盘弹出时长

    CGFloatduration = [[infoobjectForKey:UIKeyboardAnimationDurationUserInfoKey]floatValue];

    //获取键盘Rect

    CGRectendKeyboardRect = [[infoobjectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];

    CGSizekeyboardSize = endKeyboardRect.size;

    //self.view动画

    [UIViewanimateWithDuration:durationanimations:^{

    //键盘的高度

    CGFloatkeyBoardToBottom = keyboardSize.height;

    //获取当前输入框控件

    UITextField*currentTF;

    //这个里面放入当前控制器对应的textFIeld数组即可,就是这个数组

    for(UITextField*TFin@[_oldPassWordTF,_nowPassWordTF,_confirmPassWordTF]) {

    if([TFisFirstResponder]) {

    currentTF = TF;

    };

    }

    //控件底部到self.view底部的距离

    CGFloatviewToBottom;

    //定义输入框与键盘距离

    CGFloatspaceHeight =10;

    viewToBottom =self.view.frame.size.height-CGRectGetMaxY(currentTF.frame) - spaceHeight;

    //键盘遮挡区域高度

    CGFloatoffSet = viewToBottom -keyBoardToBottom;

    if(offSet <0) {

    //导航条高度

    CGFloatnavHeight =64;

    //self.view应该上移的高度

    self.view.frame=CGRectMake(0, offSet + navHeight,self.view.bounds.size.width,self.view.bounds.size.height);

    }

    }completion:^(BOOLfinished) {

    }];

    }

    3.2取消键盘时,self.view恢复原样

    - (void)keyboardWillHide:(NSNotification*) notification{

    //获取键盘通知信息

    NSDictionary*info = [notificationuserInfo];

    //获取键盘弹出时长

    CGFloatduration = [[infoobjectForKey:UIKeyboardAnimationDurationUserInfoKey]floatValue];

    [UIViewanimateWithDuration:durationanimations:^{

    CGFloatnavHeight =64;

    self.view.frame=CGRectMake(0, navHeight,self.view.bounds.size.width,self.view.bounds.size.height);

    }completion:^(BOOLfinished) {

    }];

    }

    时间比较紧,有时间再弄个通用的,如果有更好的想法或有不足之处可联系我,791903178qq,谢谢

    相关文章

      网友评论

          本文标题:iOS开发 多个textfield简单键盘处理

          本文链接:https://www.haomeiwen.com/subject/phzxvttx.html