import SwiftUI
class CounterModel: ObservableObject {
@Published var count = 0
}
struct CounterView: View {
@StateObject var model = CounterModel()
var body: some View {
VStack(spacing: 20) {
Text("\(model.count)")
.font(.largeTitle)
.accessibilityLabel("Current count")
Button("Increase") {
model.count += 1
}
.buttonStyle(.borderedProminent)
.accessibilityLabel("Increase count button")
}
.padding()
}
}
struct CounterView_Previews: PreviewProvider {
static var previews: some View {
CounterView()
}
}We created CounterModel as a class that follows ObservableObject. It has a @Published property count that SwiftUI watches for changes.
In CounterView, we use @StateObject to create and keep the model alive. The view shows the current count in a large font.
The button calls a closure that increases count. Because count is @Published, the view updates automatically.
We added accessibility labels for better support.