GeometryReader vs ViewThatFits and Layout

SwiftUI Mid-level Swift 5.7+ iOS 16+ Reviewed By Alok Singh

Pick the fix

Show three buttons side by side if they fit, otherwise stacked vertically, including at large Dynamic Type sizes. Best tool?

Options
Hint 1 of 1

Which API measures the options for you?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A ViewThatFits { HStack { buttons } ; VStack { buttons } }

Correct. It measures and picks the first layout that fits.

Why not the others?
  • B GeometryReader and compare width with a magic number. It works but is fragile and greedy, and it ignores text size.
  • C AnyLayout chosen by horizontalSizeClass. Size class doesn't tell you whether these buttons fit at the current text size.
  • D Always use VStack. It wastes space when the buttons would fit.

30-second answer

GeometryReader gives you the proposed size, but it takes all available space and pushes layout into manual math. For 'pick whichever fits', use ViewThatFits (iOS 16). To switch between HStack and VStack while keeping state, use AnyLayout. For custom arrangements, write a Layout. Use GeometryReader mainly for reading sizes, often in a background.

Practise saying it · 45 s. No recording, just a timer

Explain how you build adaptive layouts in SwiftUI.

Say your answer out loud, then check which of these points you covered:

  • ViewThatFits for 'whichever fits'
  • AnyLayout keeps state
  • Layout for custom arrangements
  • GeometryReader sparingly

Deep dive

ViewThatFits tries its children in order and shows the first that fits.

AnyLayout keeps child identity when switching layouts, so state and animation survive.

Layout has two methods: sizeThatFits and placeSubviews.

onGeometryChange (iOS 18 API, back-deployed to iOS 16) reads sizes without a GeometryReader.

Common mistakes

  • Wrapping whole screens in GeometryReader.
  • Switching HStack/VStack with if/else and losing state.
  • Hard-coding device widths.

Senior take & follow-ups

Seniors reach for the highest-level tool first and explain GeometryReader's greedy sizing.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do you read a view's size without changing layout?

    Show hint

    onGeometryChange, or a GeometryReader in .background.

  2. Why does AnyLayout keep state?

    Show hint

    The children keep the same identity.

From the author

Catalog - UI

Made by the author: browse UIKit and SwiftUI components with live demos, and copy their code snippets into your project.

Suggest a fix if something here is wrong or out of date.