Michael Behan

Follow @mbehan on Micro.blog.

Incorporating SwiftUI Views in a UIKit Layout

Mixing some SwiftUI in with your UIKit app is a great way to start using it for real without having to commit to fundamentally changing how you build your app. Doing so requires some boilerplate and when what you want to start with is a single view that only makes up a small part of a screen it might seem overly onerous.

This almost put me off, but I saw it through and turned the boilerplate into an extension on UIViewController which will add your SwiftUI View on top of a placeholder UIView that has been laid out with constraints (in my use case, from a storyboard).

extension UIViewController {
    func addSwiftUIView<Content>(_ swiftUIView: Content, for placeholder: UIView) where Content: View {
        let swiftUIController = UIHostingController(rootView: swiftUIView)
        self.addChild(swiftUIController)

        guard let swiftUIView = swiftUIController.view else { return }
        swiftUIView.translatesAutoresizingMaskIntoConstraints = false
        placeholder.addSubview(swiftUIView)
        swiftUIController.didMove(toParent: self)
        swiftUIView.constrain(to: placeholder)
    }
}