Skip to content

Instantly share code, notes, and snippets.

@JenssRey
Created June 25, 2021 08:54
Show Gist options
  • Save JenssRey/51fb410e639818c67baef561233b22b6 to your computer and use it in GitHub Desktop.
Save JenssRey/51fb410e639818c67baef561233b22b6 to your computer and use it in GitHub Desktop.
UIViewController extension for adding a SwiftUI View
import UIKit
import SwiftUI
// Credits to: https://www.avanderlee.com/swiftui/integrating-swiftui-with-uikit/
extension UIViewController {
/// Add a SwiftUI `View` as a child of the input `UIView`.
/// - Parameters:
/// - swiftUIView: The SwiftUI `View` to add as a child.
/// - view: The `UIView` instance to which the view should be added.
func addSubSwiftUIView<Content>(_ swiftUIView: Content, to view: UIView) where Content : View {
let hostingController = UIHostingController(rootView: swiftUIView)
/// Add as a child of the current view controller.
addChild(hostingController)
/// Add the SwiftUI view to the view controller view hierarchy.
view.addSubview(hostingController.view)
/// Setup the contraints to update the SwiftUI view boundaries.
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
let constraints = [
hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
hostingController.view.leftAnchor.constraint(equalTo: view.leftAnchor),
view.bottomAnchor.constraint(equalTo: hostingController.view.bottomAnchor),
view.rightAnchor.constraint(equalTo: hostingController.view.rightAnchor)
]
NSLayoutConstraint.activate(constraints)
/// Notify the hosting controller that it has been moved to the current view controller.
hostingController.didMove(toParent: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment