iOS监听键盘事件

添加监听

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

键盘弹出事件

#pragma mark - NSNotification
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    self.showKeyBoard = YES;
    [self setNeedsUpdateConstraints];
    [self updateConstraintsIfNeeded];
    [self.superview layoutIfNeeded];
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    NSNumber *time = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    [UIView animateWithDuration:[time longValue]  animations:^{
        [self mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.superview.mas_bottom).offset(0);
        }];
        CGFloat offset = Is_IphoneX ? 24:0;
        [self.superview mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.superview.superview).offset(offset-height);
        }];
        [self.superview layoutIfNeeded];
        [self.superview.superview layoutIfNeeded];
    }];
}

键盘消失事件

- (void)keyboardWillHide:(NSNotification *)aNotification
{
    self.showKeyBoard = NO;
    [self setNeedsUpdateConstraints];
    [self updateConstraintsIfNeeded];
    [self layoutIfNeeded];
    NSDictionary *userInfo = [aNotification userInfo];
    NSNumber *aValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    [UIView animateWithDuration:[aValue longValue] animations:^{
        [self mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.superview.mas_bottom).offset(BottomChatInputViewHeight);
        }];
        CGFloat offset = Is_IphoneX ? 24:0;

        [self.superview mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.superview.superview).offset(offset);
        }];
        [self.superview.superview layoutIfNeeded];
        [self layoutIfNeeded];
    }];
}

你可能感兴趣的:(iOS监听键盘事件)