I'm in the unenviable position of needing the current UIViewController to keep an external library happy. Essentially, I need to do this in SwiftUI:
import LibraryOutOfMyControl
ViewControllerReader { viewController in
Button("Action") {
LibraryOutOfMyControl.action(with: viewController)
}
}
My simple attempt below functions correctly but I'm relying on makeUIViewController always being immediately followed by updateUIViewController. Is the a reasonable assumption or should I set everything up assuming updateUIViewController might never be called?
struct ViewControllerReader<Content>: UIViewControllerRepresentable where Content: View {
@ViewBuilder var content: (UIViewController) -> Content
func makeUIViewController(context: Context) -> UIHostingController<Content> {
UIHostingController(rootView: content(UIViewController()))
}
func updateUIViewController(_ uiViewController: UIHostingController<Content>, context: Context) {
uiViewController.rootView = content(uiViewController)
uiViewController.view.isUserInteractionEnabled = context.environment.isEnabled
}
func sizeThatFits(_ proposal: ProposedViewSize, uiViewController: UIHostingController<Content>, context: Context) -> CGSize? {
uiViewController.sizeThatFits(in: proposal.replacingUnspecifiedDimensions())
}
}