swift - 以编程方式更新约束?

标签 swift autolayout constraints programmatically

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

当按下按钮时 exchangesViewActivated 发生变化并调用函数。

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

Die subview 和 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 以停用它还不够吗?我必须调用其他东西吗?

最佳答案

每次您调用 setUpLayout() 方法时,

setUpLayout() 都会添加新的约束。您必须保存约束引用并在下次更新它。

例如。

// class variable 
var bottomConstraint:NSLayoutConstraint? = nil

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

然后更新约束

bottomConstraint.constant = 100
bottomConstraint.isActive = true

关于swift - 以编程方式更新约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50885944/

相关文章:

ios - 在 CitrusPay 网关 swift ios 中设置卡类型的问题

ios - 使用 NSLayoutConstraint 垂直居中两个 View

android - 以编程方式获取约束的 id

swift - 更改 UITableViewCell 的 intrinsicContentSize 是如何工作的?

ios - constraintsWithVisualFormat 无法正常工作?

sql - 使 NOT NULL 约束仅适用于新行

sql - 为 HSQLDB 中的列指定默认空字符串的正确方法?

ios - 从 Obj-c 到 swift 的 Segue 找不到属性

ios - 在 Swift/Objective-C 中重用 tableviewcell 时,属性标签不会消失

ios - 使用闭包而不是 UIBarButtonItem 的选择器参数但不使用弱 self