0
0
iOS Swiftmobile~5 mins

Why state drives reactive UI updates in iOS Swift

Choose your learning style9 modes available
Introduction

State holds the current data of your app. When state changes, the app updates what you see automatically. This keeps the app fresh and interactive without extra work.

When you want a button to show different text after tapping it.
When you need to update a list when new items are added.
When a toggle switch changes the app's theme color.
When a form input updates a preview in real time.
When you want to show or hide parts of the screen based on user actions.
Syntax
iOS Swift
@State private var variableName: Type = initialValue
Use @State to mark variables that can change and affect the UI.
Changing a @State variable tells SwiftUI to redraw the parts of the screen that use it.
Examples
A simple true/false state to track if a switch is on.
iOS Swift
@State private var isOn: Bool = false
An integer state to keep track of a number, like a counter.
iOS Swift
@State private var count: Int = 0
A string state to hold text input from the user.
iOS Swift
@State private var username: String = ""
Sample App

This app shows a toggle switch and a text label. When you flip the switch, the text changes automatically because the @State variable isOn updates and triggers the UI to refresh.

iOS Swift
import SwiftUI

struct ContentView: View {
  @State private var isOn: Bool = false

  var body: some View {
    VStack(spacing: 20) {
      Text(isOn ? "Switch is ON" : "Switch is OFF")
        .font(.title)
      Toggle("Toggle Switch", isOn: $isOn)
        .padding()
    }
    .padding()
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}
OutputSuccess
Important Notes

Always use @State for simple, local state inside a view.

Changing state variables causes SwiftUI to re-run the view's body and update the screen.

Do not change state variables directly from outside the view; use bindings or other state management tools.

Summary

State holds data that can change and affect the UI.

Mark variables with @State to make the UI update automatically when they change.

This makes your app interactive and keeps the screen in sync with your data.