问题描述
我想在watchOS6中创建SwiftUI视图时注入一个EnvironmentObject.
I want to inject an EnvironmentObject while creating a SwiftUI view in watchOS6.
但是由于WKHostingController需要具体类型,所以我无法执行以下ContentView().environmentObject(UserData())
But since WKHostingController expects a Concrete type I am not able to do the following ContentView().environmentObject(UserData())
class HostingController: WKHostingController<ContentView> {
override var body: ContentView {
return ContentView().environmentObject(UserData())
}
}
此代码失败,并出现以下错误:
This code fails with the following error:
我看到了这样的解决方法:在watchOS中使用environmentObject ,这似乎是一种hack,而不是适当的解决方案.
I have seen workaround like this :Using environmentObject in watchOS this seems like a hack instead of a proper solution.
我在Twitter上问了一个watchOS工程师,他的回答是将.environmentObject(UserData())
放在ContentView()
的主体内.我尝试这样做,但是Xcode报告错误.
I asked a watchOS engineer on Twitter regarding the same and his reply was to place .environmentObject(UserData())
inside the body of ContentView()
. I tried doing that but Xcode reports an error.
那么有没有人找到一种方法来做同样的事情?
So has anyone found a way to do the same ?
推荐答案
链接的替代方法使用AnyView
,这是一个非常糟糕的主意.苹果工程师在其他几个问题和推文中已经解释说,AnyView只应在叶子视图上使用,否则会严重影响性能.
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.
对于第二个选项(将environmentObject
放在ContentView
内),它可以正常工作.这里有一个例子:
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")
}
}
}
}
这篇关于如何在watchOS6中注入.environmentObject()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!