Changing Auto Layout Anchor Constrains

2019-09-01 04:24发布

I have a UITextField, and I'm trying to change its position when the keyboard comes up. More specifically, I want to move the text field up so that it sits just above the keyboard. My code looks something like this

let textField = myCustomTextField()

override func viewDidLoad() {
     //set up textfield here
     //constrains blah blah

     textField.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor,
          constant: -view.bounds.height * 0.05).isActive = true

     //more constraints
}

What I want to do next is change that constraint so that it raises up the textfield when the keyboard comes up. My code looks like this:

 @objc func keyboardWillShow(notification: NSNotification) {
     textField.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor,
          constant: -view.bounds.height * 0.05).constant = 200 //200 is a sample number I have a math calculation there
     textField.layoutIfNeeded()
} 

That doesn't work because referencing that constraint by just using constraint(equalTo: constant:) doesn't actually return any constraint. Is there any way to reference that constraint without creating a variable for each constraint I want to change and changing its constant?

1条回答
成全新的幸福
2楼-- · 2019-09-01 04:55

The problem with your code is that you create a second constraint instead of changing the current , you should hold a reference to the created on and change it's constant , you can reference it like this

var bottomCon:NSLayoutConstraint?

override func viewDidLoad() {

   bottomCon =  textField.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor,
      constant: -view.bounds.height * 0.05)
   bottomCon.isActive = true

 }

then you can access it in any method and play with constant property

Edit: for every constraint you create assign identifier and access it as below

 let textFieldCons= button.constraints.filter { $0.identifier == "id" }
 if let botCons = textField.first {
      // process here
    }
查看更多
登录 后发表回答