class Container:ObservableObject {
weak var controller:NSViewController?
}
class HSHostingController<Content>:NSHostingController<ModifiedContent<Content,SwiftUI._EnvironmentKeyWritingModifier<Container?>>> where Content : View {
init(rootView:Content) {
let container = Container()
let modified = rootView.environmentObject(container) as! ModifiedContent<Content, _EnvironmentKeyWritingModifier<Container?>>
super.init(rootView: modified)
container.controller = self
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
how problematic is it to be using _EnvironmentKeyWritingModifier
I think the easiest option would be to use AnyView and define your type as a subclass of NSHostingController<AnyView>, but if for whatever reason you want to avoid AnyView here's another option:
class Container: ObservableObject {
weak var controller: NSViewController?
}
protocol RootViewModifyingHostingController {
associatedtype ModifiedRootView: View
associatedtype RootView: View
@ViewBuilder static func modify(rootView: RootView, container: Container) -> ModifiedRootView
}
class MyHostingController<RootView: View>: NSHostingController<MyHostingController.ModifiedRootView>, RootViewModifyingHostingController {
init(rootView: RootView) {
let container = Container()
let modified = Self.modify(rootView: rootView, container: container)
super.init(rootView: modified)
container.controller = self
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
static func modify(rootView: RootView, container: Container) -> some View {
rootView
.environmentObject(container)
}
}
In the snippet you're referring to you can really just use it nearly as-is. You would create an instance of the hosting controller, MyHostingController(rootView: Text('hello')) etc.
I can be more helpful if you can say what you're trying to do and what issue you're running into.