我试图在键盘出现时向上移动视图,而在键盘隐藏时向下移动视图。
我遇到的问题是高度似乎有所不同: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)")
}
}
}
答案 0 :(得分:0)
问题是您正在使用UIKeyboardFrameBeginUserInfoKey
。
该通知将为您提供开始帧和结束帧,因此您可以相应地移动视图。结束帧将是键盘动画结束的位置,因此它是最终位置。您应该使用此。
我曾经大量使用此扩展程序,我认为它是用于Swift 2
func getKeyboardHeight(notification: NSNotification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.CGRectValue().height
}
您应该能够针对Swift 4进行更新,但是最重要的部分是使用结束帧而不是开始