美文网首页
iOS监听键盘事件

iOS监听键盘事件

作者: iOS扫地僧 | 来源:发表于2017-12-02 14:46 被阅读0次

    添加监听

    [[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监听键盘事件

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