更改自动布局锚点约束 [英] Changing Auto Layout Anchor Constrains

查看:105
本文介绍了更改自动布局锚点约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UITextField,并且我试图在键盘抬起时更改其位置.更具体地说,我想向上移动文本字段,使其位于键盘上方.我的代码看起来像这样

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

那是行不通的,因为仅使用constraint(equalTo: constant:)引用该约束实际上并没有返回任何约束.有什么方法可以引用该约束,而无需为我要更改的每个约束及其常量定义一个变量?

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?

推荐答案

您的代码存在的问题是您创建了第二个约束而不是更改当前约束,您应该保留对on的引用并更改其常量,可以这样引用它

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

为每个约束创建一个分配标识符并按以下方式访问它

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
    }

这篇关于更改自动布局锚点约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆