iOS效果 - 处理键盘弹出事件

简介

在开发过程中,我们基本上都要进行键盘事件的处理,在键盘弹出的时候为了避免输入框被挡住,我们需要把整个view向上移动一定距离,键盘隐藏的时候又恢复到原来的位置。今天给大家分享的方法适合处理像微信那样输入框跟随键盘无缝同步上移。

  1. 实现的效果
  2. 实现思路
  3. Demo下载

    实现的效果

keyboardDemo

实现思路

  1. 添加监听,在viewDidLoad方法中添加键盘弹出和隐藏监听

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
  2. 实现keyboardWillShow:和keyboardWillHide:方法

    - (void)keyboardWillShow:(NSNotification *)noti {
    
        NSInteger Duration = [[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] integerValue];//获取键盘显示动画持续时间
    UIViewAnimationOptions option = ([[noti.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue] );//获取键盘显示动画曲线
    CGFloat bottom = [[noti.userInfo objectForKey: UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;//获取键盘高度
    self.BottomConstraint.constant = bottom;//frame的改变方法,根据具体情况来写
    [UIView animateWithDuration:Duration delay:0 options:option animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {}];
    
        [self.button setTitle:@"收键盘" forState:UIControlStateNormal];
    }
    
    - (void)keyboardWillHide:(NSNotification *)noti {
    
        NSInteger Duration = [[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] integerValue];//获取键盘隐藏动画持续时间
    UIViewAnimationOptions option = ([[noti.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue] );//获取键盘隐藏动画曲线
    self.BottomConstraint.constant = 0;//frame的改变方法,根据具体情况来写
    
        [UIView animateWithDuration:Duration  delay:0 options:option animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {}];
    
        [self.button setTitle:@"出键盘" forState:UIControlStateNormal];
    }
    
  3. 移除通知,重写dealloc方法

    - (void)dealloc {
    
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    }

Demo下载

点我下载