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
selectedAgeState 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
- The slider starts by showing the value in the
selectedAgedata box (100). - If the user moves the slider, the value in the
selectedAgedata box updates. - If the data in the
selectedAgedata box changes, SwiftUI automatically updates the slider on the screen to reflect the change.