美文网首页iOS基本功iOS开发攻城狮的集散地
iOS监听键盘弹出和收回时输入框位置的改变

iOS监听键盘弹出和收回时输入框位置的改变

作者: cong_cong聪 | 来源:发表于2017-01-12 23:35 被阅读0次
  • 在iOS上有两个通知可以监听键盘弹出和收回:

UIKeyboardWillShowNotification(弹出)和UIKeyboardWillHideNotification(收回)。可以分别监听两个通知调整输入框的位置。但也有一个监听起来更为方便的通知UIKeyboardWillChangeFrameNotification(直接监听键盘的frame改变,弹出或收回)代码如下:

//监听键盘弹出或收回通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
  • 当键盘frame改变(弹出和收回)时的操作:
- (void)keyboardChange:(NSNotification *)note{
    
    //拿到键盘弹出的frame
    CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    //修改底部输入框的约束
    self.bottomConstrain.constant = [UIScreen mainScreen].bounds.size.height - frame.origin.y;
    
    //键盘弹出所需时长
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //添加输入框弹出和收回动画
    [UIView animateWithDuration:duration animations:^{
       
        //立即刷新进行重新布局
        [self.view layoutIfNeeded];
    }];
}

  • 移除通知
//移除通知
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
动图.gif

相关文章

网友评论

    本文标题:iOS监听键盘弹出和收回时输入框位置的改变

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