swift/iOS-键盘高度值在通知之间更改,但实际高度保持不变
当键盘出现/消失时,我有一个试图移动的视图。这是基本代码swift/iOS-键盘高度值在通知之间更改,但实际高度保持不变,ios,swift,Ios,Swift,当键盘出现/消失时,我有一个试图移动的视图。这是基本代码 func registerForKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(_:)), name: .UIKeyboardDidShow, object: nil) NotificationCenter.default.addObs
func registerForKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(_:)), name: .UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(_:)), name: .UIKeyboardDidHide, object: nil)
}
@objc func keyboardWasShown(_ notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0 {
print("\n\n\n\(keyboardSize.height)\n\n")
self.view.frame.origin.y -= keyboardSize.height
}
}
}
@objc func keyboardWillBeHidden(_ notification: NSNotification) {
self.view.frame.origin.y = 0
}
第一次调用它时,它打印258.0,视图向上移动。后续调用打印216.0。键盘每次向上移动的幅度相同。第一次将视图移动到正确的位置(视图的底部刚好位于键盘上方),随后将底部(42px)移到键盘后面
知道是什么原因吗?使用
UIKeyboardFrameBeginUserInfoKey
而不是UIKeyboardFrameEndUserInfoKey
此外,我建议您只使用一个通知来处理框架的所有更改,如下所示:
//Add keyboard did Layout change notification
NotificationCenter.default.addObserver(self,selector: #selector(self.keyboardNotification(notification:)),name:NSNotification.Name.UIKeyboardWillChangeFrame,object: nil)
然后像这样实现它
@objc func keyboardNotification(notification: NSNotification) {
if let userInfo = notification.userInfo {
let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let endFrameY = endFrame?.origin.y ?? 0
let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue
let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)
if endFrameY >= UIScreen.main.bounds.size.height {
//Change This
//self.signInButtonBottomConstraint?.constant = 0.0
} else {
//Modify This
//self.signInButtonBottomConstraint?.constant -= (endFrame?.size.height ?? 0.0)
}
UIView.animate(withDuration: duration,
delay: TimeInterval(0),
options: animationCurve,
animations: { self.view.layoutIfNeeded() },
completion: nil)
}