【问题标题】:Updating Constraints programmatically?以编程方式更新约束?
【发布时间】:2018-11-25 21:52:02
【问题描述】:

我有一个 UIView 的子类,我想操作一个约束但它不起作用。

当按下按钮时,会发生 ViewActivated 更改并调用函数。

var exchangesViewActivated = false {
    didSet {
        if exchangesViewActivated == true {
            setExchangesView()
        } else {
            setUpLayout()
        }
    }
}

模具子视图和 translatesAutoresizingMaskIntoConstraints 已设置。

func setUpLayout() {

    bottomContainer.heightAnchor.constraint(equalToConstant: 500).isActive = true


    bottomContainer.leadingAnchor.constraint(equalTo: scrollViewContrainer.leadingAnchor).isActive = true
    bottomContainer.trailingAnchor.constraint(equalTo: scrollViewContrainer.trailingAnchor).isActive = true
    bottomContainer.topAnchor.constraint(equalTo: configBar.bottomAnchor).isActive = true
    bottomContainer.bottomAnchor.constraint(equalTo: scrollViewContrainer.bottomAnchor).isActive = true

}

现在我想通过调用这个函数来操作约束:

 func setExchangesView() {

bottomContainer.bottomAnchor.constraint(equalTo: scrollViewContrainer.bottomAnchor).isActive = false

        bottomContainer.heightAnchor.constraint(equalToConstant: 500).isActive = false
        bottomContainer.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
}

但此约束保持激活状态:

bottomContainer.heightAnchor.constraint(equalToConstant: 500).isActive

我错过了什么吗?将约束设置为 false 以停用它还不够吗?我必须打电话给其他人吗?

【问题讨论】:

    标签: swift autolayout constraints programmatically


    【解决方案1】:

    setUpLayout() 每次调用 setUpLayout() 方法时都会添加新的约束。您必须保存约束引用并下次更新。

    例如。

    // class variable 
    var bottomConstraint:NSLayoutConstraint? = nil
    
    bottomConstraint = bottomContainer.heightAnchor.constraint(equalToConstant: 500)
    bottomConstraint.isActive = true
    

    后来更新约束

    bottomConstraint.constant = 100
    bottomConstraint.isActive = true
    

    【讨论】:

    • 我有一个问题,也许你知道,如果我从它的 supervie 中移除一个 UIView,它的所有约束也会被移除吗?
    【解决方案2】:

    这不会停用旧的约束,因为它会停用新创建的约束

    var heightCon:NSLayoutConstraint!
    var botCon:NSLayoutConstraint!
    

    //

    heightCon = bottomContainer.heightAnchor.constraint(equalToConstant: 500)
    heightCon.isActive = true
    
    botCon = bottomContainer.bottomAnchor.constraint(equalTo: scrollViewContrainer.bottomAnchor)
    botCon.isActive = true
    

    然后您可以轻松引用约束并停用它们并添加新约束

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-15
      • 2021-12-20
      • 2015-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多