Updating Auto Layout with Trait Collection Changes

suggest change

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 } }

}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Size Classes and Adaptivity:
* Updating Auto Layout with Trait Collection Changes

Table Of Contents
12 UIView
15 UIColor
26 UIImage
28 CALayer
30 NSDate
40 iBeacon
49 NSTimer
79 NSURL
84 Size Classes and Adaptivity
87 AWS SDK
96 NSData
101 Segues
104 EventKit
105 NSBundle
106 SiriKit
111 StoreKit
117 3D Touch
119 Keychain
122 Block
141 AirDrop
144 UISlider
145 Carthage
146 HealthKit
151 plist
157 MVVM
164 UIPhoenix
166 Simulator
168 NSArray
169 OpenGL
175 Core Data
179 MyLayout
180 UIFont
189 Security
200 Codable