import SwiftUI
class CounterViewModel: ObservableObject {
@Published var number: Int = 0
func increase() {
number += 1
}
func decrease() {
number -= 1
}
}
struct ContentView: View {
@StateObject private var viewModel = CounterViewModel()
var body: some View {
VStack(spacing: 40) {
Text("\(viewModel.number)")
.font(.largeTitle)
HStack(spacing: 60) {
Button("-") {
viewModel.decrease()
}
.font(.title)
Button("+") {
viewModel.increase()
}
.font(.title)
}
}
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}This app uses the MVVM pattern by separating the logic from the view. The CounterViewModel class holds the number and methods to change it. It uses @Published so SwiftUI updates the UI automatically when the number changes.
The ContentView creates a @StateObject instance of the ViewModel. The text showing the number binds to viewModel.number. The buttons call the ViewModel's increase and decrease methods. This keeps the UI simple and the logic in the ViewModel, following MVVM principles.