我已订阅keyboardWillShowNotification
并keyboardWillHideNotification
在我的 UI 中移动。我注意到,当我通过点击“Go”按钮关闭键盘时,keyboardWillShowNotification
会调用两次(从而重置我的一些约束)但是如果通过在键盘(MacBook)上按回车键关闭,则不会调用两次。
我怎样才能避免它被调用两次?为什么这种行为甚至存在?我找不到任何提及它(很多对它的引用被输入视图调用两次......等等),但从来没有被解雇。
这是我的代码:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWasDismissed(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
和...
@objc func keyboardNotification(notification: NSNotification) {
guard
let animationDuration = notification.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? Double,
let animationCurve = notification.userInfo?["UIKeyboardAnimationCurveUserInfoKey"] as? NSNumber,
let frameEnd = notification.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? CGRect,
let frameBegin = notification.userInfo?["UIKeyboardFrameBeginUserInfoKey"]
else {
print("No userInfo recived from NSNotification.Name.UIKeyboardWillShow")
return
}
print("WILL SHOW")
let margin = self.view.safeAreaLayoutGuide
constraintsWhenKeyboardVisible = [
boxOffice.leadingAnchor.constraint(equalTo: margin.leadingAnchor),
boxOffice.trailingAnchor.constraint(equalTo: margin.trailingAnchor),
boxOffice.bottomAnchor.constraint(equalTo: margin.bottomAnchor),
boxOffice.topAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -(frameEnd.height + 50))
]
NSLayoutConstraint.deactivate(boxOfficeFinalConstraints)
NSLayoutConstraint.activate(constraintsWhenKeyboardVisible)
UIView.animate(withDuration: animationDuration,
delay: TimeInterval(0),
options: UIView.AnimationOptions(rawValue: animationCurve.uintValue),
animations: {
self.boxOffice.answerField.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
self.view.layoutIfNeeded()
},
completion: nil)
}
@objc func keyboardWasDismissed(notification: NSNotification) {
guard
let animationDuration = notification.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? Double,
let animationCurve = notification.userInfo?["UIKeyboardAnimationCurveUserInfoKey"] as? NSNumber
else {
print("No userInfo recived from NSNotification.Name.UIKeyboardWillShow")
return
}
print("WILL HIDE")
//print(notification)
NSLayoutConstraint.deactivate(self.constraintsWhenKeyboardVisible)
NSLayoutConstraint.activate(self.boxOfficeFinalConstraints)
UIView.animate(withDuration: animationDuration,
delay: TimeInterval(0),
options: UIView.AnimationOptions(rawValue: animationCurve.uintValue),
animations: {
self.boxOffice.answerField.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMinXMinYCorner]
self.view.layoutIfNeeded()
},
completion: nil)
}