一, 在viewDidload() 中 绑定通知,并添加键盘监听
其中绑定的 keyboardWillShow 会有动画, KeyboardDidShow 不会有 动画
func viewDidload(){
NotificationCenter.default.addObserver(self, selector: #selector(PasscodePane.keyboardWillHide(_:)),name:NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(PasscodePane.keyboardWillShow(_:)),name:NSNotification.Name.UIKeyboardWillShow, object: nil)
}
//释放
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}
func keyboardWillShow(_ sender: Notification) {
//获取键盘的frame
guard let keyboardFrame = (sender.userInfo?[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue else {
return
}
//如果边框=0也返回
if(keyboardFrame.height == nill || keyboardFrame.height == 0){return;}
UIView.animate(withDuration: 0.1, animations: {
self.containerCenterConstraint?.update(offset: -keyboardFrame.height/2)
self.layoutIfNeeded()
})
}
func keyboardWillHide(_ sender: Notification) {
UIView.animate(withDuration: 0.1, animations: {
self.containerCenterConstraint?.update(offset: 0)
self.layoutIfNeeded