Auto Layout & Constraints

June 02, 2026 1 min read

Auto Layout positions views with rules ("constraints") so your UI looks right on every iPhone and iPad size and orientation.

Constraints in code

NSLayoutConstraint.activate([
    label.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
    label.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
    label.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16)
])

Key ideas

  • Pin edges to the safe area to avoid the notch and home indicator.
  • Set translatesAutoresizingMaskIntoConstraints = false on views you constrain in code.
  • Use anchors (topAnchor, leadingAnchor...) — they are the cleanest API.
Tip: UIStackView + a few constraints handles most layouts with very little code.

Summary

Auto Layout makes UI responsive. Use anchors, respect the safe area, and let stack views do the heavy lifting.