我试图在键盘出现时向上移动视图,在键盘隐藏时向下移动 .
我遇到的问题是高度似乎不同:KBH1输出216,KBH2输出260 .
这导致视图向下移动得比最初移动的距离更远 .
我该如何纠正这个?
extension UIViewController {
func addKeyboardFunctions() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboardEx))
// tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear), name: Notification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear), name: Notification.Name.UIKeyboardWillShow, object: nil)
}
@objc func keyboardWillAppear(_ notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0{
self.view.frame.origin.y -= keyboardSize.height
print("KBH: \(keyboardSize.height)")
}
}
}
@objc func keyboardWillDisappear(_ notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += keyboardSize.height
print("KBH: \(keyboardSize.height)")
}
}
}