Created
August 16, 2023 21:05
-
-
Save Wouter01/4e22c9e8a30bc2b9c182e8dff7b84f70 to your computer and use it in GitHub Desktop.
SwiftUI EnvironmentObservable
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 | |
import Observation | |
@propertyWrapper | |
struct EnvironmentObservable<Value: AnyObject & Observable>: DynamicProperty { | |
@Environment var wrappedValue: Value | |
public init(_ objectType: Value.Type) { | |
_wrappedValue = .init(objectType) | |
} | |
public init() { | |
_wrappedValue = .init(Value.self) | |
} | |
private var store: Bindable<Value>! | |
var projectedValue: Bindable<Value> { | |
store | |
} | |
mutating func update() { | |
store = Bindable(wrappedValue) | |
} | |
} | |
@Observable | |
class Model { | |
var someField = "Hello" | |
} | |
struct ContentView: View { | |
@EnvironmentObservable var model: Model | |
var body: some View { | |
VStack { | |
Text(model.someField.uppercased()) | |
TextField("", text: $model.someField) | |
} | |
.padding() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment