【问题标题】:Changing Auto Layout Anchor Constrains更改自动布局锚约束
【发布时间】:2018-03-05 18:45:13
【问题描述】:

我有一个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:) 引用该约束实际上不会返回任何约束。有什么方法可以引用该约束,而无需为我要更改的每个约束创建变量并更改其常量?

【问题讨论】:

    标签: swift uitextfield ios-autolayout


    【解决方案1】:

    您的代码的问题是您创建了第二个约束而不是更改 current ,您应该持有对 created on 的引用并更改它的常量,您可以像这样引用它

    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 { $0.identifier == "id" }
     if let botCons = textField.first {
          // process here
        }
    

    【讨论】:

    • 有没有办法将该变量存储在不在我的视图控制器中的某个地方?就像在我将这些约束应用到的任何视图中一样?因为假设我想更改 20 个约束,我是否必须将所有这些作为单独的变量存储在视图控制器中?
    • 我没有使用故事板来设置约束,所以我试图以编程方式设置标识符,但我没有做任何事情。我正在尝试通过执行 constrain.identifier = "some identifier" 来设置约束标识符,但是当我遍历项目、约束时,它们都没有任何标识符。只能通过storyboard添加标识符吗?
    猜你喜欢
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 2014-01-27
    相关资源
    最近更新 更多