0
0
iOS Swiftmobile~20 mins

@ObservedObject 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 updates automatically using @ObservedObject to watch changes.
Target UI
-------------------
|   Counter: 0    |
|                 |
|   [ Increase ]  |
-------------------
Create a class CounterModel that holds an integer count and can increase it.
Use @Published in CounterModel to notify changes.
Create a SwiftUI view that uses @ObservedObject to watch CounterModel.
Display the current count in a Text view.
Add a Button labeled 'Increase' that calls the increase method in CounterModel.
Starter Code
iOS Swift
import SwiftUI

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

struct CounterView: View {
    // TODO: Add @ObservedObject property for CounterModel
    
    var body: some View {
        VStack {
            // TODO: Show 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
Task 5
Solution
iOS Swift
import SwiftUI

class CounterModel: ObservableObject {
    @Published var count = 0
    
    func increase() {
        count += 1
    }
}

struct CounterView: View {
    @ObservedObject var counter = CounterModel()
    
    var body: some View {
        VStack(spacing: 20) {
            Text("Counter: \(counter.count)")
                .font(.largeTitle)
            Button("Increase") {
                counter.increase()
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(8)
        }
        .padding()
    }
}

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

We created CounterModel as a class conforming to ObservableObject. The @Published property count automatically notifies views when it changes. In CounterView, we use @ObservedObject to watch an instance of CounterModel. The Text shows the current count, and the Button calls increase() to update the count. SwiftUI updates the UI automatically when count changes.

Final Result
Completed Screen
-------------------
|   Counter: 0    |
|                 |
|   [ Increase ]  |
-------------------
When the user taps 'Increase', the number after 'Counter:' increases by 1.
The UI updates immediately without needing to refresh manually.
Stretch Goal
Add a 'Reset' button that sets the counter back to zero.
💡 Hint
Add a reset() method in CounterModel that sets count to 0, then add a Button in the view that calls reset().