在watchOS中使用environmentObject [英] Using environmentObject in watchOS
问题描述
我正在尝试在watchOS6应用中使用environmentObject
将数据模型绑定到视图.
I am trying to use environmentObject
in a watchOS6 app to bind my data model to my view.
我已经在Xcode 11中创建了一个简单的独立Watch应用.
I have created a simple, stand-alone Watch app in Xcode 11.
我创建了一个新的DataModel
类
import Combine
import Foundation
import SwiftUI
final class DataModel: BindableObject {
let didChange = PassthroughSubject<DataModel,Never>()
var aString: String = "" {
didSet {
didChange.send(self)
}
}
}
在我的ContentView
结构中,我使用@EnvironmentObject
-
In my ContentView
struct I bind this class using @EnvironmentObject
-
struct ContentView : View {
@EnvironmentObject private var dataModel: DataModel
var body: some View {
Text($dataModel.aString.value)
}
}
最后,我尝试将DataModel
的实例注入HostingController
类中的环境-
Finally, I attempt to inject an instance of the DataModel
into the environment in the HostingController
class -
class HostingController : WKHostingController<ContentView> {
override var body: ContentView {
return ContentView().environmentObject(DataModel())
}
}
但是,我得到一个错误:
But, I get an error:
Cannot convert return expression of type '_ModifiedContent<ContentView, _EnvironmentKeyWritingModifier<DataModel?>>' to return type 'ContentView'
错误是因为WKHostingController
是需要具体类型的泛型-在这种情况下为WKHostingController<ContentView>
.
The error is because the WKHostingController
is a generic that needs a concrete type - WKHostingController<ContentView>
in this case.
由于UIHostingController
不是通用类,因此类似的方法也可以完美地与iOS应用程序中的UIHostingController
配合使用.
A similar approach works perfectly with UIHostingController
in an iOS app because UIHostingController
isn't a generic class.
还有其他方法可以将环境注入watchOS视图吗?
Is there some other way to inject the environment to a watchOS view?
推荐答案
您可以使用类型擦除,对于SwiftUI View
,可以使用AnyView
.
You can use type erasure, AnyView
in the case of SwiftUI View
.
我将重构WKHostingController
以返回AnyView
.
这对我来说似乎编译的很好.
This seems to compile fine on my end.
class HostingController : WKHostingController<AnyView> {
override var body: AnyView {
return AnyView(ContentView().environmentObject(DataModel()))
}
}
这篇关于在watchOS中使用environmentObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!