iOS監(jiān)聽鍵盤彈出和收回時(shí)輸入框位置的改變

  • 在iOS上有兩個(gè)通知可以監(jiān)聽鍵盤彈出和收回:

UIKeyboardWillShowNotification(彈出)和UIKeyboardWillHideNotification(收回)。可以分別監(jiān)聽兩個(gè)通知調(diào)整輸入框的位置。但也有一個(gè)監(jiān)聽起來更為方便的通知UIKeyboardWillChangeFrameNotification(直接監(jiān)聽鍵盤的frame改變,彈出或收回)代碼如下:

//監(jiān)聽鍵盤彈出或收回通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
  • 當(dāng)鍵盤frame改變(彈出和收回)時(shí)的操作:
- (void)keyboardChange:(NSNotification *)note{
    
    //拿到鍵盤彈出的frame
    CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    //修改底部輸入框的約束
    self.bottomConstrain.constant = [UIScreen mainScreen].bounds.size.height - frame.origin.y;
    
    //鍵盤彈出所需時(shí)長
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //添加輸入框彈出和收回動畫
    [UIView animateWithDuration:duration animations:^{
       
        //立即刷新進(jìn)行重新布局
        [self.view layoutIfNeeded];
    }];
}

  • 移除通知
//移除通知
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
動圖.gif
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容