Constraints Not Updating When Keyboard Appears

╄→гoц情女王★ 提交于 2019-12-24 18:23:04

问题


I am making a sign up screen and would like to update a few top anchors so that when the keyboard appears, the top anchor constant decreases and the keyboard doesn't cover any text fields.

I have created a topConstant variable:

var constraintConstant: CGFloat = 35

And have set up my views as follows:

view.addSubview(passwordTextField)
passwordTextField.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 25).isActive = true
passwordTextField.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -25).isActive = true
passwordTextField.heightAnchor.constraint(equalToConstant: 50).isActive = true
passwordTextField.topAnchor.constraint(equalTo: emailTextField.bottomAnchor, constant: constraintConstant).isActive = true

Then I have written this code:

func textFieldDidBeginEditing(_ textField: UITextField) {
    constraintConstant = 15
    view.layoutIfNeeded()
}

I'n not sure why the constriants aren't updating. Any ideas?


回答1:


Ok. I had this problem when i first started out on iOS with Swift. See the problem is with your understanding of anchors.

The constant that you specify doesn't function like how you are expecting it to. (You are expecting it to function like some kind of listener which will keep updating based on the update in the value of the variable. It doesn't) It will just take the value of the variable at the time of setting and then not look back unless you access that anchor and change the constant manually.

Which is why you have to store the instance of the anchor and change the constant maually like this.

Define the constraint variable:

var topAnchorConstraint: NSLayoutConstraint!

Store the appropriate constraint in the variable

topAnchorConstraint = passwordTextField.topAnchor.constraint(equalTo: emailTextField.bottomAnchor, constant: 35)
topAnchorConstraint.isActive = true

Now you need to change the constant as required.

func textFieldDidBeginEditing(_ textField: UITextField) {
    UIView.animate(withDuration: 1.0, animations: {
        self.topAnchorConstraint.constant = 15
        self.view.layoutIfNeeded()

    }, completion: nil)
}



回答2:


You need

var topCon:NSLayoutConstraint!

//

topCon = passwordTextField.topAnchor.constraint(equalTo: emailTextField.bottomAnchor, constant: constraintConstant)
topCon.isActive = true

//

func textFieldDidBeginEditing(_ textField: UITextField) {
    topCon.constant = 15
    view.layoutIfNeeded()
}


来源:https://stackoverflow.com/questions/52042162/constraints-not-updating-when-keyboard-appears

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!