Browse Questions

Answer: Auto Layout calculates view frames at runtime by solving a system of linear equations defined by your constraints. Priority determines which constraints can break when there's a conflict.

Code Example:

let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)

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

// Priority — 1000 = required, 750 = high, 250 = low
let widthConstraint = label.widthAnchor.constraint(equalToConstant: 200)
widthConstraint.priority = .defaultHigh  // 750 — can be broken if needed
widthConstraint.isActive = true

// Content Hugging — how hard a view resists growing
label.setContentHuggingPriority(.required, for: .horizontal)

// Compression Resistance — how hard a view resists shrinking
label.setContentCompressionResistancePriority(.required, for: .horizontal)