swift 是否以编程方式更新约束?

tktrz96b  于 2023-02-15  发布在  Swift
关注(0)|答案(2)|浏览(162)

我有一个UIView的子类,我想操作一个约束,但它不起作用。
按下按钮时,exchangesViewActivated发生变化,并调用函数。

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

芯片子视图和平移自动调整大小掩膜插入约束已设置。

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
}

但此约束仍处于激活状态:
底部容器高度锚点约束(等于常量:500)。处于活动状态
我错过了什么吗?将约束设置为false来禁用它还不够吗?我必须调用其他东西吗?

ki1q1bka

ki1q1bka1#

每次调用setUpLayout()方法时,setUpLayout()都会添加新约束。必须保存约束引用,并在下次更新它。
例如。

// class variable 
var bottomConstraint:NSLayoutConstraint? = nil

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

和以后的更新约束

bottomConstraint.constant = 100
bottomConstraint.isActive = true
zdwk9cvp

zdwk9cvp2#

这不会像取消激活新创建的约束那样取消激活旧约束

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

然后,您可以轻松地参照约束、取消激活约束以及添加新约束

相关问题