更改自动布局锚点约束

Changing Auto Layout Anchor Constrains

我有一个 UITextField,我正试图在键盘出现时改变它的位置。更具体地说,我想将文本字段向上移动,使其正好位于键盘上方。我的代码看起来像这样

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
}

我接下来要做的是更改该约束,以便它在键盘出现时提升文本字段。我的代码如下所示:

 @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()
} 

那是行不通的,因为仅使用 constraint(equalTo: constant:) 来引用该约束实际上并不 return 任何约束。有没有什么方法可以在不为每个我想更改的约束创建变量并更改其常量的情况下引用该约束?

你的代码的问题是你创建了第二个约束而不是改变当前的,你应该持有对创建的引用并改变它的常量,你可以像这样引用它

var bottomCon:NSLayoutConstraint?

override func viewDidLoad() {

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

 }

然后你可以用任何方法访问它并使用常量 属性

编辑:为您创建的每个约束分配标识符并按如下方式访问它

 let textFieldCons= button.constraints.filter { [=11=].identifier == "id" }
 if let botCons = textField.first {
      // process here
    }