两种主要的自动布局约束创建方式(代码创建):
-
addConstraints()
scrollView.addSubview(statusButton) scrollView.addConstraints([ statusButton.topAnchor.constraint(equalTo: scrollView.topAnchor, constant:12), statusButton.leftAnchor.constraint(equalTo: scrollView.leftAnchor, constant:16), statusButton.heightAnchor.constraint(equalToConstant: 36), ]) scrollView.addSubview(dateRangeButton) scrollView.addConstraints([ dateRangeButton.topAnchor.constraint(equalTo: scrollView.topAnchor, constant:12), dateRangeButton.leftAnchor.constraint(equalTo: statusButton.rightAnchor, constant:4), dateRangeButton.heightAnchor.constraint(equalToConstant: 36), ]) scrollView.addSubview(transactionTypeButton) scrollView.addConstraints([ transactionTypeButton.topAnchor.constraint(equalTo: scrollView.topAnchor, constant:12), transactionTypeButton.leftAnchor.constraint(equalTo: dateRangeButton.rightAnchor, constant:4), transactionTypeButton.heightAnchor.constraint(equalToConstant: 36), ])
-
activate()
这实际上等价于 addConstraints(),NSLayoutConstraint.activate() 方法可以一次性创建所有约束,也可以调用多次,分批次创建约束,比如这样:stockNameLabel = UILabel() stockNameLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(stockNameLabel) NSLayoutConstraint.activate([ stockNameLabel.topAnchor.constraint(equalTo: topAnchor, constant: 24), stockNameLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16), ]) stockCodeLabel = UILabel() stockCodeLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(stockCodeLabel) NSLayoutConstraint.activate([ stockCodeLabel.topAnchor.constraint(equalTo: stockNameLabel.bottomAnchor, constant: 8), stockCodeLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16), ])
-
修改约束
首先创建一个约束并保持该约束的引用:
// 创建约束,同时保持一个引用 separatorViewTop = separatorView.topAnchor.constraint(equalTo:view.topAnchor, constant: investmentAccountSection.intrinsicHeight) // 添加约束 NSLayoutConstraint.activate([ ... // Separator view separatorView.heightAnchor.constraint(equalToConstant: 1), separatorViewTop!, separatorView.leadingAnchor.constraint(equalTo: view.leadingAnchor), separatorView.trailingAnchor.constraint(equalTo: view.trailingAnchor), ... ])
修改约束并立即调用 updateConstraintsIfNeeded():
self.separatorViewTop?.constant = self.investmentAccountSection.intrinsicHeight self.view.updateConstraintsIfNeeded()