我正在尝试移动 UIView
的 constraintToBottom.constant
,其中显示后我的 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)
})
}
}
当我打印 constraintToBottom.constant
时,它显示:
constant 346.0
然而,UIView
仍然像往常一样在键盘上方不可见。我做错了什么?
更新
如建议的那样,减号可以解决问题,但还有额外的空间,看起来像这样:
最佳答案
需要重新布局 View
self.constraintToBottom.constant = -1 * keyboardSize.height
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
print("constant", self.constraintToBottom.constant)
})
关于ios - 在键盘上方显示 UIView 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52692446/