Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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