Making an app adaptive – that is, responding to size class changes by changing your layout – often involves lots of help from the Auto Layout system. One of the primary ways apps become adaptive is by updating the active Auto Layout constraints when a view's size class changes.
For example, consider an app that uses a UIStackView to arrange two UILabels. We might want these labels to stack on top of each other in horizontally compact environments, but sit next to each other when we have a little more room in horizontally regular environments.
class ViewController: UIViewController {
var stackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
stackView = UIStackView()
for text in ["foo", "bar"] {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = text
stackView.addArrangedSubview(label)
}
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
updateAxis(forTraitCollection: traitCollection)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateAxis(forTraitCollection: traitCollection)
}
private func updateAxis(forTraitCollection traitCollection: UITraitCollection) {
switch traitCollection.horizontalSizeClass {
case .regular:
stackView.axis = .horizontal
case .compact:
stackView.axis = .vertical
case .unspecified:
print("Unspecified size class!")
stackView.axis = .horizontal
}
}
}