问题描述
我试图在 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
类
I created a new DataModel
class
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
在这种情况下.
The error is because the WKHostingController
is a generic that needs a concrete type - WKHostingController<ContentView>
in this case.
类似的方法与 iOS 应用中的 UIHostingController
完美配合,因为 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?
推荐答案
你可以使用类型擦除,AnyView
在 SwiftUI View
的情况下.
You can use type erasure, AnyView
in the case of SwiftUI View
.
我会重构 WKHostingController
以返回 AnyView
.
I would refactor WKHostingController
to return AnyView
.
这对我来说似乎编译得很好.
This seems to compile fine on my end.
class HostingController : WKHostingController<AnyView> {
override var body: AnyView {
return AnyView(ContentView().environmentObject(DataModel()))
}
}
这篇关于在 watchOS 中使用 environmentObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!