I'm not sure if this is an antipattern in this brave new SwiftUI world we live in, but essentially I have an @EnvironmentObject with some basic user information saved in it that my views can call.
I also have an @ObservedObject that owns some data required for this view.
When the view appears, I want to use that @EnvironmentObject to initialize the @ObservedObject:
struct MyCoolView: View {
@EnvironmentObject userData: UserData
@ObservedObject var viewObject: ViewObject = ViewObject(id: self.userData.UID)
var body: some View {
Text("\(self.viewObject.myCoolProperty)")
}
}
Unfortunately I can't call self on the environment variable until after initialization:
"Cannot use instance member 'userData' within property initializer; property initializers run before 'self' is available."
I can see a few possible routes forward, but they all feel like hacks. How should I approach this?
@EnvironmentObject is part of the family of SwiftUI Property Wrappers that can make working with SwiftUI views a little easier. Sharing data between views can be challenging when working in SwiftUI, especially when we have a lot of child views being dependent on the same piece of data.
A property wrapper type that subscribes to an observable object and invalidates a view whenever the observable object changes.
By default, SwiftUI assumes that you don't want to localize stored strings, but if you do, you can first create a localized string key from the value, and initialize the text view with that. Using a key as input triggers the init(_:tableName:bundle:comment:) method instead.
Here is the approach (the simplest IMO):
struct MyCoolView: View {
@EnvironmentObject var userData: UserData
var body: some View {
MyCoolInternalView(ViewObject(id: self.userData.UID))
}
}
struct MyCoolInternalView: View {
@EnvironmentObject var userData: UserData
@ObservedObject var viewObject: ViewObject
init(_ viewObject: ViewObject) {
self.viewObject = viewObject
}
var body: some View {
Text("\(self.viewObject.myCoolProperty)")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With