在键盘上方显示 UIView 无法正常工作

Show UIView above keyboard not working properly

我正在尝试将 UIViewconstraintToBottom.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 仍然像往常一样在键盘上方不可见。我做错了什么?

更新

如建议的那样,减号可以解决问题,但还有额外的 space,看起来像这样:

您需要重新布局视图

self.constraintToBottom.constant = -1 * keyboardSize.height
UIView.animate(withDuration: 0.3, animations: {
     self.view.layoutIfNeeded()
     print("constant", self.constraintToBottom.constant)
})