我试图在键盘出现时向上移动视图,在键盘隐藏时向下移动 .
我遇到的问题是高度似乎不同: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)")
}
}
}
1 回答
问题是您正在使用
UIKeyboardFrameBeginUserInfoKey
.通知将为您提供开始帧和结束帧,以便您可以相应地移动视图 . 结束帧将是键盘动画结束的位置,因此它的最终位置 . 你应该使用这个 .
我以前经常使用这个扩展,我认为它适用于Swift 2
你应该能够为Swift 4更新它,但最重要的部分是使用结束帧而不是开始