0
0
iOS Swiftmobile~15 mins

@StateObject for observable objects in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Counter Screen
A simple screen that shows a number and a button to increase it. The number is stored in an observable object using @StateObject to keep the state.
Target UI
-------------------
|   Counter: 0    |
|                 |
|  [ Increase ]   |
-------------------
Create an observable class with a published integer property called count.
Use @StateObject in the view to create and observe the observable object.
Display the current count in a Text view.
Add a button labeled 'Increase' that increments the count when tapped.
Starter Code
iOS Swift
import SwiftUI

class CounterModel: ObservableObject {
    // TODO: Add @Published count property
}

struct CounterView: View {
    // TODO: Create @StateObject for CounterModel

    var body: some View {
        VStack(spacing: 20) {
            // TODO: Display count here
            // TODO: Add Increase button here
        }
        .padding()
    }
}

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

class CounterModel: ObservableObject {
    @Published var count = 0
}

struct CounterView: View {
    @StateObject private var counter = CounterModel()

    var body: some View {
        VStack(spacing: 20) {
            Text("Counter: \(counter.count)")
                .font(.largeTitle)
                .accessibilityLabel("Current count")
                .accessibilityValue("\(counter.count)")
            Button("Increase") {
                counter.count += 1
            }
            .buttonStyle(.borderedProminent)
            .accessibilityLabel("Increase count button")
        }
        .padding()
    }
}

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

We created CounterModel as an observable object with a @Published property count. This means SwiftUI will watch for changes to count and update the UI automatically.

In CounterView, we use @StateObject to create and own the CounterModel instance. This ensures the state stays alive as long as the view exists.

The Text shows the current count, and the Button increases the count by 1 when tapped. Accessibility labels help screen readers describe the UI clearly.

Final Result
Completed Screen
-------------------
|   Counter: 0    |
|                 |
|  [ Increase ]   |
-------------------
Tapping the 'Increase' button adds 1 to the count number displayed.
The number updates immediately on screen.
Screen reader announces the updated count after each tap.
Stretch Goal
Add a 'Reset' button that sets the count back to zero.
💡 Hint
Add another Button below 'Increase' that sets counter.count = 0 when tapped.