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,252評論 4 61
  • 【一】 曾憶亭榭滿秋色,半江煙雨半江荷。聞君偏愛云間臥。 昨夜雪飄馬蹄過,欲笑還顰淚先落。此生唯羨云中鶴。 ――《...
    悒郁的肖像閱讀 541評論 19 19
  • 談寫作·請賞一個贊 作者:元宿周期表 如果有很多很多贊,我不在乎唱個蓮花落。我們愛數字。《小王子》里說:大人熱愛數...
    簡黛玉閱讀 10,590評論 7 284
  • 今天最大的事情莫過于川普獲得總統大選勝利,其實一直都沒太關注,作為搬磚群眾,自己的生活都沒照料好,哪有時間想這些國...
    本天才傳說閱讀 130評論 0 0