我试图将constraintToBottom.constant
的{{1}}移到键盘上显示的UIView
所在的位置。我设置了UITextField
观察者,但是由于某种原因,它不起作用。
Notification
当我打印override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
UIView.animate(withDuration: 0.3, animations: {
self.constraintToBottom.constant = keyboardSize.height
print("constant", self.constraintToBottom.constant)
})
}
}
时,它显示:
常数346.0
但是,constraintToBottom.constant
仍然像往常一样在键盘上方不可见。我在做什么错了?
更新
如建议的那样,减号可以解决问题,但是还有额外的空间,它看起来像这样:
答案 0 :(得分:1)
您需要重新布局视图
self.constraintToBottom.constant = -1 * keyboardSize.height
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
print("constant", self.constraintToBottom.constant)
})