Swift 监听键盘弹出和收回
2021-09-24 本文已影响0人
leblanc_i
注册通知
// 注册键盘即将出现通知
NotificationCenter.default.addObserver(self, selector: #selector(keyboardShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
// 注册键盘即将隐藏通知
NotificationCenter.default.addObserver(self, selector: #selector(keyboardHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
监听事件
/// 监听键盘即将出现事件
@objc func keyboardShow(_ noti: Notification) {
App.log("键盘即将出现")
let info = noti.userInfo
let kbRect = (info?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
UIView.animate(withDuration: 0.2) {
self.transform = CGAffineTransform(translationX: 0, y: -(kbRect?.size.height ?? 0) / 2)
}
}
/// 监听键盘即将隐藏事件
@objc func keyboardHide(_ noti: Notification) {
App.log("键盘即将隐藏")
UIView.animate(withDuration: 0.2) {
self.transform = CGAffineTransform(translationX: 0, y: 0)
}
}
移除通知
// 移除键盘监听
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)