Created
October 27, 2020 15:12
-
-
Save mykolaharmash/87e4733423b08e787ee797b6a5570999 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
class Counter: ObservableObject { | |
@Published var count: Int | |
init(_ count: Int) { | |
self.count = count | |
} | |
func increment() { | |
count = count + 1 | |
} | |
} | |
struct CounterView: View { | |
@ObservedObject var counter: Counter | |
var body: some View { | |
Text(String(counter.count)) | |
Button("+ 1", action: { counter.increment() }) | |
} | |
} | |
struct ContentView: View { | |
@StateObject var counter = Counter(0) | |
@State var random: Int = 0 | |
var body: some View { | |
VStack { | |
CounterView(counter: counter) | |
Spacer() | |
Text(String(random)) | |
Button("Random", action: { random = Int.random(in: 1...10) }) | |
}.font(.system(size: 26)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment