Using environmentObject in watchOS

微笑、不失礼 提交于 2019-12-04 00:28:46

You can use type erasure, AnyView in the case of SwiftUI View.

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()))
    }
}

For anyone like Brett (in the comments) who was getting

"Property 'body' with type 'AnyView' cannot override a property with type 'ContentView'"

I got the same error because I hadn't replaced the return value and wrapped the ContentView being returned.

ie. this is what my first attempt looked like.. notice the WKHostingController<ContentView> that should be WKHostingController<AnyView>

class HostingController : WKHostingController<ContentView> {
    override var body: AnyView {
        return AnyView(ContentView().environmentObject(DataModel()))
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!