Skip to content

Instantly share code, notes, and snippets.

@antonyalkmim
Created September 10, 2021 13:04
Show Gist options
  • Save antonyalkmim/e6e47b5fd9912d6a625ad6616395b1ab to your computer and use it in GitHub Desktop.
Save antonyalkmim/e6e47b5fd9912d6a625ad6616395b1ab to your computer and use it in GitHub Desktop.
SwiftUI+UIView.swift
import UIKit
import SwiftUI
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 addSubview<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)
}
}
extension UIView {
/// 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 addSubview<Content>(_ swiftUIView: Content, viewController: UIViewController) where Content: View {
let hostingController = UIHostingController(rootView: swiftUIView)
/// Add as a child of the current view controller.
viewController.addChild(hostingController)
/// Add the SwiftUI view to the view controller view hierarchy.
addSubview(hostingController.view)
/// Setup the contraints to update the SwiftUI view boundaries.
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
let constraints = [
hostingController.view.topAnchor.constraint(equalTo: topAnchor),
hostingController.view.leftAnchor.constraint(equalTo: leftAnchor),
bottomAnchor.constraint(equalTo: hostingController.view.bottomAnchor),
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: viewController)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment