UIKitMidMCQ

What is `UIStackView` and when should you use it?

Test your knowledge:

Explanation & Code

Answer: UIStackView arranges views in a horizontal or vertical line and manages all constraints for you. It removes the need to manually write spacing and distribution constraints.

Code Example:

// Vertical stack with spacing
let stack = UIStackView(arrangedSubviews: [titleLabel, subtitleLabel, actionButton])
stack.axis = .vertical
stack.spacing = 12
stack.alignment = .leading   // .fill, .center, .leading, .trailing
stack.distribution = .fill   // .fillEqually, .equalSpacing, .equalCentering

// Add/remove views dynamically
stack.addArrangedSubview(newLabel)
stack.removeArrangedSubview(oldLabel)
oldLabel.removeFromSuperview()

// Hide a view without removing it (stack adjusts automatically)
subtitleLabel.isHidden = true  // stack collapses the space

// Nested stacks — very powerful for complex layouts
let hStack = UIStackView(arrangedSubviews: [icon, vStack])
hStack.axis = .horizontal
hStack.spacing = 8

When to use: Almost always prefer UIStackView over manual constraints for linear arrangements — it's simpler, more maintainable, and easier to animate.

Rate your understanding:

Ready to practice more UIKit?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.