0
0
iOS Swiftmobile~15 mins

Why state drives reactive UI updates in iOS Swift - Build It to Prove It

Choose your learning style9 modes available
Build: Counter Screen
A simple screen that shows a number and a button. When you tap the button, the number increases. The number updates automatically because the UI reacts to the state change.
Target UI
-------------------
|    Counter: 0   |
|                 |
|   [ Increase ]  |
-------------------
Display a number starting at 0
Add a button labeled 'Increase'
When the button is tapped, increase the number by 1
The displayed number updates automatically when it changes
Starter Code
iOS Swift
import SwiftUI

struct CounterView: View {
    // TODO: Add state variable here

    var body: some View {
        VStack(spacing: 20) {
            // TODO: Show the current count here

            Button("Increase") {
                // TODO: Increase the count here
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(8)
        }
        .padding()
    }
}

struct CounterView_Previews: PreviewProvider {
    static var previews: some View {
        CounterView()
    }
}
Task 1
Task 2
Task 3
Solution
iOS Swift
import SwiftUI

struct CounterView: View {
    @State private var count = 0

    var body: some View {
        VStack(spacing: 20) {
            Text("Counter: \(count)")
                .font(.largeTitle)
                .accessibilityLabel("Current count")

            Button("Increase") {
                count += 1
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(8)
            .accessibilityHint("Increases the counter by one")
        }
        .padding()
    }
}

struct CounterView_Previews: PreviewProvider {
    static var previews: some View {
        CounterView()
    }
}

This app uses a @State variable called count to hold the current number. When the button is tapped, we increase count by 1. SwiftUI watches this @State variable and automatically updates the UI to show the new number. This is how state drives reactive UI updates: changing the state triggers the UI to refresh without extra code.

We also added accessibility labels and hints so screen readers can describe the UI clearly, making the app friendly for everyone.

Final Result
Completed Screen
-------------------
|    Counter: 5   |
|                 |
|   [ Increase ]  |
-------------------
Tapping the 'Increase' button adds 1 to the counter number.
The displayed number updates immediately to show the new count.
Stretch Goal
Add a 'Reset' button that sets the counter back to zero.
💡 Hint
Add another Button below the 'Increase' button that sets the @State count variable to 0 when tapped.