Swiftui - How do I initialize an observedObject using an environmentobject as a parameter?

前端 未结 2 1985
执笔经年
执笔经年 2020-11-30 12:34

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

相关标签:
2条回答
  • 2020-11-30 13:02

    Here is an easy way to to it:

    struct MyCoolView: View {
        @EnvironmentObject var userData: UserData
    
        var body: some View {
            Observe(obj: ViewObject(id: userData.UID)) { viewObject in
                 Text("\(viewObject.myCoolProperty)")
            }
        }
    }
    

    With this helper that makes it work:

    struct Observe<T: ObservableObject, V: View>: View {
        @ObservedObject var obj: T
        let content: (T) -> V
        var body: some View { content(obj) }
    }
    
    0 讨论(0)
  • 2020-11-30 13:16

    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)")
        }
    }
    
    0 讨论(0)
提交回复
热议问题