Skip to content
Tutorials Center
My learning

Topics

Lesson 128 of 146 ยท Platforms and Ecosystem

SwiftUI State, Bindings and Layout

Go deeper into SwiftUI - which property wrapper to use, bindings, the layout size negotiation, stacks, frames, grids and NavigationStack - with runnable layout and navigation stand-ins.

The SwiftUI overview showed what a view is and how state drives the screen. Real apps quickly raise sharper questions. Which of the six or seven property wrappers do I use here? Why does my Text ignore my frame? Why does a Spacer push things around the way it does? How do I move between screens without a pile of booleans?

This lesson answers those questions in three parts: state and bindings (who owns data), layout (how a parent and a child agree on a size) and navigation (how screens stack). SwiftUI needs an Apple platform and Xcode, so the SwiftUI listings are read-only. Two ideas, the layout negotiation and the navigation path, are plain algorithms, so we model them with small stand-ins you can run and change right here. The stand-in types are ours, not SwiftUI's.

Part 1: choosing the right state tool

Ask one question about every piece of data: who owns it? The answer picks the wrapper.

Data Owner Tool
A toggle, a text field's text, a selected tab, local to one view This view @State
The same value, edited by a child view A parent @Binding in the child
A model class shared by several views A parent or the app @Observable class: @State to create it, plain property to receive it
Edit a property of a model with controls Whoever holds the model @Bindable
A system or app-wide value (color scheme, locale, your own services) The environment @Environment
A small setting kept between launches UserDefaults @AppStorage
Which text field has the keyboard This view @FocusState
UI state restored with the scene The scene @SceneStorage
flowchart TD
    Q{"Who owns the data?"}
    Q -->|"This view only"| S["@State"]
    Q -->|"A parent owns it,<br/>I just edit it"| B["@Binding"]
    Q -->|"A shared model object"| M["@Observable class<br/>@State / property / @Bindable"]
    Q -->|"The system or app provides it"| E["@Environment"]
    Q -->|"It must survive relaunch"| A["@AppStorage / @SceneStorage"]

Decide ownership first; the wrapper follows.

@State and @Binding

@State is for simple values owned by one view. SwiftUI stores the value outside the view struct (the struct is recreated constantly) and re-runs body when it changes. Mark it private, because only this view should write it. Pass it to children as a @Binding, written with a $.

Swift
// Read-only example: needs SwiftUI.
import SwiftUI

struct VolumeControl: View {
    @Binding var volume: Double           // owned by the parent

    var body: some View {
        HStack {
            Image(systemName: "speaker.fill")
            Slider(value: $volume, in: 0...1)
        }
    }
}

struct PlayerView: View {
    @State private var volume = 0.5
    @State private var isMuted = false

    var body: some View {
        VStack {
            VolumeControl(volume: $volume)    // pass a binding, not a copy
            Toggle("Mute", isOn: $isMuted)
            Text(isMuted ? "Muted" : "Volume \(Int(volume * 100))%")
        }
        .padding()
    }
}

The same $ gives you a binding to a part of a value: $user.name for a struct, $todo.isDone inside ForEach($todos). If you need a computed binding, build one with Binding(get:set:), for example to clamp or convert a value. Binding.constant(true) is handy in previews.

Do not use @State for data a view receives from outside. @State keeps the first value it saw; later values passed by the parent are ignored, which looks like "my view never updates". Use a plain let or var for read-only input, @Binding for read/write input.

Models: @State to own, plain to receive, @Bindable to edit

For model objects use an @Observable class (see Observation). The view that creates the model keeps it in @State. Children that only read it take it as an ordinary property. Children that want $model.property bindings declare it @Bindable.

Swift
// Read-only example: needs SwiftUI.
import SwiftUI
import Observation

@Observable
final class Recipe {
    var title = "Pancakes"
    var servings = 4
    var isFavorite = false
}

struct RecipeScreen: View {
    @State private var recipe = Recipe()         // created and owned here

    var body: some View {
        VStack {
            RecipeHeader(recipe: recipe)         // read only
            RecipeEditor(recipe: recipe)         // edits
        }
    }
}

struct RecipeHeader: View {
    let recipe: Recipe
    var body: some View { Text("\(recipe.title) serves \(recipe.servings)") }
}

struct RecipeEditor: View {
    @Bindable var recipe: Recipe
    var body: some View {
        Form {
            TextField("Title", text: $recipe.title)
            Stepper("Servings: \(recipe.servings)", value: $recipe.servings, in: 1...12)
            Toggle("Favorite", isOn: $recipe.isFavorite)
        }
    }
}

RecipeHeader redraws only when title or servings change, because those are the properties its body reads.

@Environment, @AppStorage and @FocusState

Swift
// Read-only example: needs SwiftUI.
import SwiftUI

struct SettingsView: View {
    @Environment(\.colorScheme) private var colorScheme     // read a system value
    @Environment(\.dismiss) private var dismiss              // an action
    @AppStorage("username") private var username = "guest"   // stored in UserDefaults
    @FocusState private var nameIsFocused: Bool

    var body: some View {
        Form {
            TextField("Name", text: $username)
                .focused($nameIsFocused)
            Text("Current theme: \(colorScheme == .dark ? "dark" : "light")")
            Button("Done") { dismiss() }
        }
        .onAppear { nameIsFocused = true }
    }
}

@Environment reads a value that a parent (or the system) provided. You can define your own keys and inject models with .environment(model). @AppStorage is a binding that reads and writes UserDefaults, so the data survives relaunch.

Part 2: how layout works

SwiftUI layout is a short negotiation between parent and child. It has three steps and you can remember them as a conversation:

  1. The parent proposes a size to the child ("I have 300 by 600 points; what do you want?").
  2. The child chooses its own size, and the parent has to respect it.
  3. The parent places the child inside its own space.
sequenceDiagram
    participant P as Parent (HStack)
    participant C as Child (Text)
    P->>C: propose 120 x 44
    C-->>P: I need 86 x 20
    P->>P: place child at its position

Children pick their own size; that is why a Text ignores a frame that tries to force it larger.

Different views answer the proposal differently. A Text takes only as much room as its text needs (and wraps or truncates if offered less). An Image marked resizable() accepts whatever it is offered. A Color or Rectangle takes everything it is offered. A Spacer takes everything along the stack's axis and nothing across it.

The stack algorithm

HStack and VStack do the arithmetic in an order that explains most of their behavior. They subtract the spacing, then ask children from least flexible to most flexible, giving each an equal share of the room that remains. Fixed-size views get theirs first, and flexible views like Spacer and Color share what is left. The runnable model below is a simplified version of that idea (our own types):

Swift A simplified HStack layout (stand-in types)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first row is the classic "label on the left, value on the right" layout: the two fixed views keep 80 and 60, and the spacer gets the remaining 160. With spacing the gaps come out of the room first (two gaps of 8 leave 284), so the spacer shrinks to 144. When two flexible views compete they split the leftover 200 into 100 each. The capped view is asked first (it is less flexible), takes at most 70, and the other receives the other 180: that is why .frame(maxWidth:) on one child changes how its siblings are sized.

Frames, padding and order

Modifiers wrap a view in a new one that changes the proposal or the result, so order matters (the overview showed this with backgrounds). Remember what each wrapper does:

Swift
// Read-only example: needs SwiftUI.
import SwiftUI

struct LayoutDemo: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            Text("Fixed frame")
                .frame(width: 200, height: 44)           // a 200x44 box; the text sits centered in it
                .background(.yellow)

            Text("Flexible frame")
                .frame(maxWidth: .infinity, alignment: .leading)   // fill the width, text at the leading edge
                .background(.mint)

            Text("Padding, then background")
                .padding()                                // proposes less room to the text
                .background(.orange)                      // the color covers text + padding

            HStack {
                Text("Left")
                Spacer()                                  // pushes the next view to the trailing edge
                Text("Right")
            }

            Text("A long sentence that might need several lines on a narrow phone screen")
                .lineLimit(2)
                .layoutPriority(1)                        // keeps its room when siblings compete
        }
        .padding()
    }
}

Useful rules of thumb:

  • .frame(width:height:) creates a fixed container around the view; it does not force the view itself bigger.
  • .frame(maxWidth: .infinity) makes a container that accepts all the width offered, which is how you make a button full width.
  • .padding() shrinks the proposal for its child and adds the space back to the size it reports.
  • .fixedSize() tells a view to use its ideal size, ignoring the proposal, which stops text from wrapping or truncating.
  • Alignment is set per stack: VStack(alignment: .leading) lines children up on their leading edges. Use .alignmentGuide only for unusual cases.
  • GeometryReader gives you the proposed size, but it greedily takes all offered space and often causes surprises. Prefer layout modifiers, ViewThatFits, or the Layout protocol.

Lists of views: lazy stacks and grids

Swift
// Read-only example: needs SwiftUI.
import SwiftUI

struct PhotoGrid: View {
    let photos: [Int]
    let columns = [GridItem(.adaptive(minimum: 100), spacing: 8)]

    var body: some View {
        ScrollView {
            LazyVGrid(columns: columns, spacing: 8) {   // creates cells only as they scroll in
                ForEach(photos, id: \.self) { photo in
                    RoundedRectangle(cornerRadius: 8)
                        .fill(.blue.gradient)
                        .aspectRatio(1, contentMode: .fit)
                        .overlay { Text("\(photo)").foregroundStyle(.white) }
                }
            }
            .padding()
        }
    }
}

VStack and HStack build all children immediately, so use them for a handful of views. LazyVStack, LazyHStack, LazyVGrid and List create children on demand, so use them for long collections. ViewThatFits picks the first child that fits the space, which is a neat way to adapt a layout without measuring anything.

Part 3: navigation

NavigationStack is a stack of screens. You can let links push destinations directly, but the powerful form uses a path: an array of values that is the navigation state. Because the state is data, you can push several screens at once, pop back to the root or restore the stack after a relaunch.

Swift
// Read-only example: needs SwiftUI.
import SwiftUI

enum Route: Hashable {
    case recipe(id: Int)
    case settings
}

struct RootView: View {
    @State private var path: [Route] = []

    var body: some View {
        NavigationStack(path: $path) {
            List {
                NavigationLink("Pancakes", value: Route.recipe(id: 1))
                NavigationLink("Settings", value: Route.settings)
            }
            .navigationTitle("Home")
            .navigationDestination(for: Route.self) { route in
                switch route {
                case .recipe(let id): Text("Recipe \(id)")
                case .settings: Text("Settings")
                }
            }
        }
    }
}

Pushing a screen means appending to path; going back means removing the last element; "back to root" is path.removeAll(). Other presentation tools are .sheet(item:) and .fullScreenCover for modals, TabView for top-level sections, and NavigationSplitView for sidebar layouts.

Because the path is only an array, you can run the same logic here with a stand-in router:

Swift A navigation path as data (stand-in types)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The back stack grows and shrinks exactly like the arrow in the toolbar. A deep link such as myapp://settings/about becomes "parse the URL into [Route] and assign it to path". Keeping navigation as plain data also makes it easy to test without a UI.

Common mistakes

  • Putting the model in @State of a child that is recreated. A view that creates a model must be the one that owns it, otherwise a new model is made when the parent re-renders.
  • Using @State for a parent's value. The child shows stale data (see the warning above).
  • Heavy work in body. It can run many times a second; compute in the model.
  • Fighting layout with GeometryReader and magic numbers. Use stacks, Spacer, frame(maxWidth:), ViewThatFits.
  • Unstable ids in ForEach. Use an Identifiable id from the data, never the index of a changing array.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A child view must edit a Bool that its parent owns. What does the child declare?

    @Binding is a read/write reference to state owned elsewhere. The parent passes it with $isOn.
  2. 2. In the layout negotiation, who chooses a view's final size?

    The parent proposes, the child decides, and the parent places the result. That is why a frame cannot force a Text larger.
  3. 3. In an HStack with two fixed views and one Spacer in 300 points, how much space does the Spacer get?

    Fixed views are sized first; the flexible Spacer takes the leftover room.
  4. 4. What is the main advantage of a NavigationStack path array?

    Because the path is an array of Hashable values, you can manipulate and save it like any other state.
  5. 5. Which container creates its children only as they scroll into view?

    Lazy stacks and grids build children on demand, which is essential for long collections.

Summary

  • Pick state by ownership: @State (this view), @Binding (parent's value), @Observable model with @State/plain/@Bindable, @Environment, @AppStorage, @FocusState.
  • Never use @State for a value that is passed in from a parent.
  • Layout is a negotiation: parent proposes, child chooses, parent places. Stacks size the least flexible children first and split what is left among the flexible ones.
  • .frame, .padding, .fixedSize and Spacer shape the proposal and the result, so their order matters.
  • Use lazy stacks, grids and List for long collections and prefer layout tools over GeometryReader.
  • NavigationStack(path:) makes navigation a plain array of values you can push, pop and save.
  • Everything in this lesson that is SwiftUI is read-only; the stand-in layout and router run anywhere.

Next: Project: Calculator