How to inject .environmentObject() in watchOS6

后端 未结 1 566
猫巷女王i
猫巷女王i 2021-01-22 01:50

I want to inject an EnvironmentObject while creating a SwiftUI view in watchOS6.

But since WKHostingController expects a Concrete type I am not able to do the following

相关标签:
1条回答
  • 2021-01-22 02:14

    The workaround from the link uses AnyView, which is a very bad idea. It has been explained in several other questions and tweets from Apple engineers, that AnyView should only be used on leaf views, as there is a heavy performance hit otherwise.

    As for the second option (put the environmentObject inside ContentView), it works fine. Here you have an example:

    class UserData: ObservableObject {
        @Published var show: Bool = true
    }
    
    struct ContentView: View {
        @State var model = UserData()
    
        var body: some View {
            SubView().environmentObject(model)
        }
    }
    
    struct SubView: View {
        @EnvironmentObject var model: UserData
    
        var body: some View {
            VStack {
                Text("Tap Me!").onTapGesture {
                    self.model.show.toggle()
                }
    
                if self.model.show {
                    Text("Hello World")
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题