import SwiftUI
class CounterViewModel: ObservableObject {
@Published var count = 0
}
struct CounterView: View {
@StateObject private var viewModel = CounterViewModel()
var body: some View {
VStack(spacing: 20) {
Text("Counter: \(viewModel.count)")
.font(.largeTitle)
.accessibilityLabel("Current count")
Button("Increase") {
viewModel.count += 1
}
.buttonStyle(.borderedProminent)
.accessibilityLabel("Increase count button")
}
.padding()
}
}
struct CounterView_Previews: PreviewProvider {
static var previews: some View {
CounterView()
}
}We created a CounterViewModel class that conforms to ObservableObject. Inside it, the @Published property count holds the current number. When count changes, SwiftUI automatically updates any views observing it.
In CounterView, we use @StateObject to keep an instance of the view model. The Text view shows the current count by reading viewModel.count. The Button increments count when tapped.
This setup makes the UI update automatically without manual refresh calls, demonstrating the power of @Published properties in SwiftUI.