Created
October 5, 2020 09:48
-
-
Save kazuooooo/14f0ce42dc125ae1994d74a44f0ad22c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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