Using environmentObject in watchOS

前端 未结 3 1691
盖世英雄少女心
盖世英雄少女心 2021-02-05 05:23

I am trying to use environmentObject in a watchOS6 app to bind my data model to my view.

I have created a simple, stand-alone Watch app in Xcode 11.

相关标签:
3条回答
  • 2021-02-05 06:03

    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()))
        }
    }
    
    0 讨论(0)
  • 2021-02-05 06:08

    Adding to Matteo's awesome answer,

    If you want to use delegate then use like this:

    class HostingController : WKHostingController<AnyView> {
        override var body: AnyView {
            var contentView = ContentView()
            contentView.environmentObject(DataModel())
            contentView.delegate = self
            let contentWrapperView = AnyView(contentView)
            return contentWrapperView
        }
    }
    
    0 讨论(0)
  • 2021-02-05 06:18

    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()))
        }
    }
    
    0 讨论(0)
提交回复
热议问题