注冊通知
NotificationCenter.default.addObserver(self, selector: #selector(ComposeViewController.keyboardWillChangeFrame(node:)), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
移除通知
deinit {
NotificationCenter.default.removeObserver(self)
}
監(jiān)聽鍵盤高度變化
@objc private func keyboardWillChangeFrame(node : Notification){
//1.獲取動畫執(zhí)行的時間
let duration = node.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! Double
//2. 獲取鍵盤最終的Y值
let endFrame = (node.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
let y = endFrame.origin.y
//3.計算工具欄距離底部的間距
let margin = UIScreen.main.bounds.height - y
//4.執(zhí)行動畫
toolBarBottomCons.constant = margin
UIView.animate(withDuration: duration) {
self.view.layoutIfNeeded()
}
}
常用的通知的名字
. 監(jiān)聽軟鍵盤的彈出
.UIKeyboardWillShow
. 監(jiān)聽軟鍵盤的收起
.UIKeyboardWillHide
.監(jiān)聽軟鍵盤的高度變化
.UIKeyboardWillChangeFrame