Skip to content

Instantly share code, notes, and snippets.

@jasperblues
Last active December 23, 2020 02:50
Show Gist options
  • Save jasperblues/79fb016b9693bf600f36cf6c2267b2ab to your computer and use it in GitHub Desktop.
Save jasperblues/79fb016b9693bf600f36cf6c2267b2ab to your computer and use it in GitHub Desktop.
Adapter allowing a UIKit controller to be backed by a SwiftUI view.
class SwiftUIAdapter<Content> where Content : View {
private(set) var view: Content!
weak private(set) var parent: UIViewController!
private(set) var uiView : WrappedView
var hostingController: UIHostingController<Content>
init(view: Content, parent: UIViewController) {
self.view = view
self.parent = parent
hostingController = UIHostingController(rootView: view)
parent.addChild(hostingController)
hostingController.didMove(toParent: parent)
uiView = WrappedView(view: hostingController.view)
}
deinit {
hostingController.removeFromParent()
hostingController.didMove(toParent: nil)
}
}
@jasperblues
Copy link
Author

To Use

Override the VC's loadView method to self.view = adapter.uiView

override func loadView() {
    super.loadView()
    view = adapter.uiView
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment