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 ] | -------------------
------------------- | Counter: 0 | | | | [ Increase ] | -------------------
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() } }
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.
------------------- | Counter: 0 | | | | [ Increase ] | -------------------
@ObservedObject in a SwiftUI view?class Counter: ObservableObject {
@Published var count = 0
}
struct ContentView: View {
@ObservedObject var counter = Counter()
var body: some View {
VStack {
Text("Count: \(counter.count)")
Button("Increment") {
counter.count += 1
}
}
}
}class TimerModel: ObservableObject {
@Published var time = 0
}
struct TimerView: View {
@ObservedObject var timer: TimerModel
var body: some View {
Text("Time: \(timer.time)")
}
}Settings object and passes it to two child views. Which is the best way to share this data so both children update when settings change?Pass the test and this pattern moves unknown