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];
    }];
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.先设置监听者以及监听对象和事件 [[NSNotificationCenter defaultCenter] a...
    methodname阅读 1,791评论 0 0
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,250评论 4 61
  • 【一】 曾忆亭榭满秋色,半江烟雨半江荷。闻君偏爱云间卧。 昨夜雪飘马蹄过,欲笑还颦泪先落。此生唯羡云中鹤。 ――《...
    悒郁的肖像阅读 540评论 19 19
  • 谈写作·请赏一个赞 作者:元宿周期表 如果有很多很多赞,我不在乎唱个莲花落。我们爱数字。《小王子》里说:大人热爱数...
    简黛玉阅读 10,590评论 7 284
  • 今天最大的事情莫过于川普获得总统大选胜利,其实一直都没太关注,作为搬砖群众,自己的生活都没照料好,哪有时间想这些国...
    本天才传说阅读 130评论 0 0