将 UIView 推到键盘问题上方的动画约束

Animating constraint to push UIView above Keyboard issue

我有这个CommentViewController。它嵌入在容器视图中。在这个 CommentViewController 中,有一个用于显示评论的 UITableView 和包含一个 UITextField 和一个 UIButtonUIView。包含这 2 个对象的 UIView 通过自动布局固定在底部、右侧和左侧到安全区域以及顶部到 UITableView

现在,当用户点击 UITextField 时,整个视图(带有按钮和内部文本字段)应该被提升到键盘上方。我正在尝试为视图的底部约束设置动画,但它不起作用。

这是代码:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

}

@objc func keyboardWillShow(_ notification: NSNotification) {
    let keyboardFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue
    UIView.animate(withDuration: 0.3) {
        self.textFieldViewBottomConstraint.constant = keyboardFrame!.height
    }
}

这是故事板:

这是点击文本字段后的结果。

PS:当我点击 UITextField 时,控制台显示此消息:

2018-06-04 14:11:52.471848+0300 AppName[91846:8829073] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/d/Library/Developer/CoreSimulator/Devices/C89347A2-1598-4F31-BBAC-1F98F970A248/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles 2018-06-04 14:11:52.472588+0300 Shippers[91846:8829073] [MC] Reading from private effective user settings.

您需要在更改约束的常量后调用self.view.layoutIfNeeded()

self.textFieldViewBottomConstraint.constant = keyboardFrame!.height
   UIView.animate(withDuration: 0.3) {
    self.view.layoutIfNeeded()
}

//

 NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)

编辑:

底部约束的设置常量属性取决于哪个元素是约束中的第一个元素,所以如果约束看起来像这样

这里的文本框是第一个

textfield_Bottom = view_Bottom * multiplier + constant. —> then constant must be minus as Y axis decrease when go to up which what we want to make the view goes up when keyboard is shown

这里是第一个视图

view_Bottom = textfield_Bottom * multiplier + constant. —> then constant must be plus