iOS基本功iOS开发攻城狮的集散地

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

2017-01-12  本文已影响0人  cong_cong聪

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

//监听键盘弹出或收回通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
- (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
上一篇下一篇

猜你喜欢

热点阅读