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.