美文网首页
OC 获取键盘高度

OC 获取键盘高度

作者: Look2021 | 来源:发表于2021-08-27 14:43 被阅读0次
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChangeFrameNotification:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];

获取高度,改变某个view约束

- (void)keyboardWillChangeFrameNotification:(NSNotification *)notification {
    // 获取键盘基本信息(动画时长与键盘高度)
    NSDictionary *userInfo = [notification userInfo];
    CGRect rect = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    
    CGFloat keyboardHeight = keyboardRect.size.height;
    CGFloat keyboardDuration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    self.insertPauseView.hidden = NO;
    // 修改下边距约束
    [self.insertPauseView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).offset(-keyboardHeight);
    }];
    
    // 更新约束
    [UIView animateWithDuration:keyboardDuration animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)keyboardHide:(NSNotification *)notification {
    // 获取键盘基本信息(动画时长与键盘高度)
    NSDictionary *userInfo = [notification userInfo];

    CGFloat keyboardDuration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    self.insertPauseView.hidden = YES;
    // 修改下边距约束
    [self.insertPauseView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
    }];
    
    // 更新约束
    [UIView animateWithDuration:keyboardDuration animations:^{
        [self.view layoutIfNeeded];
    }];
}

相关文章

网友评论

      本文标题:OC 获取键盘高度

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