Skip to content

Instantly share code, notes, and snippets.

@kazuooooo
Created October 5, 2020 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazuooooo/14f0ce42dc125ae1994d74a44f0ad22c to your computer and use it in GitHub Desktop.
Save kazuooooo/14f0ce42dc125ae1994d74a44f0ad22c to your computer and use it in GitHub Desktop.
import SwiftUI
struct CounterView: View {
// Data binding with CounterView Model
@EnvironmentObject var counterViewModel: CounterViewModel
var body: some View {
return VStack {
// count value updated automatically by data binding
Text(String(self.counterViewModel.count))
HStack {
Button("+", action: {
self.counterViewModel.countUp()
})
Button("-", action: {
self.counterViewModel.countDown()
})
}
// ✅ Stepper update value internally, and it works as Model
// So, we don't need to write model logic
Stepper("Enter your age", value: self.$counterViewModel.count2, in: 0...130)
Text(String(counterViewModel.count2))
}
}
}
struct CountView_Previews: PreviewProvider {
static var previews: some View {
CounterView().environmentObject(CounterViewModel())
}
}
class CounterViewModel: ObservableObject {
// Store count for view
@Published var count = 0
@Published var count2 = 0
// Has countUp and countDown method for View
public func countUp() {
// Call CounterModel methods to increment and decrement count and update its count with returned value
count = CounterModel.incrmentCount(currentCount: count)
}
public func countDown() {
count = CounterModel.decrementCount(currentCount: count)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment