State & Binding

SwiftUI uses State and Binding to control how your views work and display information.

State: The Data Box

  • Stores Changing Information: Your State box holds information that might change, like the current score in a game, the state of a toggle switch, or text entered by the user.
  • Magic Update: Whenever the data in a State box changes, SwiftUI knows and automatically updates the parts of your screen that depend on that information.

Example

@State var selectedAge: Double = 100
  • The selectedAge State Box: This box holds a number representing the age selected. You start with a default value of 100.

Binding: The Magic Pipeline

  • Connects Data and Views: Binding is like a magic pipeline connecting a State box (your data) to a view (like a text field, toggle, or slider).
  • Two-Way Flow:
    • Changes made in the view (user moves the slider) travel along the pipeline and update the information in the State box.
    • Changes to the information in the State box (from somewhere else in your code) flow through the pipeline and update what’s shown in the view.

Example

Slider(value: $selectedAge, in: 0...255)
  • The $ Symbol: That $ symbol is the magic that creates the binding connection.

Working Together

  1. The slider starts by showing the value in the selectedAge data box (100).
  2. If the user moves the slider, the value in the selectedAge data box updates.
  3. If the data in the selectedAge data box changes, SwiftUI automatically updates the slider on the screen to reflect the change.
See forum comments
Download course materials from Github
Previous: Modifiers: Hands-On Demo Next: State & Binding: Hands-On Demo