Created
May 23, 2020 19:10
-
-
Save rayfix/1606190f572b6eb934e45f4a56701feb 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 | |
| extension View { | |
| func printType() -> Self { | |
| print(type(of: self)) | |
| return self | |
| } | |
| } | |
| // Need to make a key; all it needs is a default value. | |
| struct SecretMessageKey: EnvironmentKey { | |
| static let defaultValue = "some secret" | |
| } | |
| // We need to extend Environment with our key | |
| extension EnvironmentValues { | |
| var secretMessage: String { | |
| get { | |
| self[SecretMessageKey.self] | |
| } | |
| set { | |
| self[SecretMessageKey.self] = newValue | |
| } | |
| } | |
| } | |
| // Need to add a modifier for views so they can inject a value for the key into the environment | |
| extension View { | |
| func secretMessage(_ message: String) -> some View { | |
| environment(\.secretMessage, message) | |
| } | |
| } | |
| // We can now use the environment | |
| struct MyView: View { | |
| @Environment(\.secretMessage) var message | |
| var body: some View { | |
| Text(message) | |
| } | |
| } | |
| // Experiment with EnvironmentObject... You must remember to | |
| // inject in or your app crashes. You can only inject one instance of | |
| // a type. | |
| final class ViewModel: ObservableObject { | |
| @Published var total: Int = 0 | |
| } | |
| struct ContentView: View { | |
| @Environment(\.colorScheme) var colorScheme | |
| @EnvironmentObject var scoreboard: ViewModel | |
| @EnvironmentObject var scoreboard2: ViewModel | |
| var body: some View { | |
| VStack { | |
| MyView().secretMessage("sdfs") | |
| MyView() | |
| Text("The score is \(scoreboard.total)") | |
| Text("The score is \(scoreboard2.total)") | |
| .foregroundColor(colorScheme == .dark ? Color.purple : Color.black) | |
| }.font(.largeTitle) | |
| .secretMessage("Yay") | |
| .printType() | |
| .onAppear { | |
| self.scoreboard.total += 1 // This will modify both scoreboard and scoreboard2 ! | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment