通过修改自动布局的约束实现键盘弹出后view上推

1.通过storyb搭建view,使用自动布局。注意tableview要以下方输入框为参考。


  

2. 找到发送框名称为Vertical Space - Bottom Layout Guide的约束,并连线

  


  


3.  通过通知中心设置观察者,监听键盘弹出事件

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置观察者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChanged:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

 4. 处理事件

- (void)keyboardFrameChanged:(NSNotification *)n {
    NSLog(@"%@", n);
    
    // 取出通知中的 userInfo 中的 CGRect
    CGRect rect = [n.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    // 取出动画时长
    NSTimeInterval t = [n.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    // 修改底部约束的数值 - 视图的自动布局就发生了变化
    self.bottomConstraint.constant = rect.size.height;
    
    // 动画
    [UIView animateWithDuration:t animations:^{
        // 自动布局的动画,如果需要重新布局
        [self.view layoutIfNeeded];
    }];
}

原文地址:https://www.cnblogs.com/coderkl/p/4320308.html