How to embed a SwiftUI view into a UIKit Storyboard

Share on facebook
Share on twitter
Share on pinterest

In case you are working with storyboards you maybe wondered how you can embed a SwiftUI view into your UIKit storyboard. This can be very useful if you want to compose your views with SwiftUI with relying on the familiar storyboard functionality as well.

Maybe in your storyboard looks something like this:

And that’s how your SwiftUI view could look like:

Embedding the SwiftUI view into your storyboard is super simple, just follow the three steps below:

Step 1: Inside your storyboard file click on the + button and drag and drop a Hosting View Controller. This View Controller is capable of hosting a SwiftUI view.


Step 2: Next, create a UIHostingController subclass. Inside this class, initialise your specific SwiftUI view by using the “init? (coder aDecoder: NSCoder)” initialiser as you see above. ⠀

//Create a UIHostingController class that hosts your SwiftUI view
class SwiftUIViewHostingController: UIHostingController<MySwiftUIView> {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder, rootView: MySwiftUIView())
    }
}

struct MySwiftUIView: View {
    var body: some View {
        //..
    }
}


Step 3: Now we’re ready to take this UIHostingController subclass and assign it the the Hosting Controller in our storyboard.⠀


That’s it! If you now run your app, the UIHostingController initialises your SwiftUI view properly. And that’s how you embed your SwiftUI view into your UIKit storyboard 🎊⠀


I hope you enjoyed this tutorial! If you want to learn more about SwiftUI, check out our other tutorials! Also make sure you follow us on Instagram and subscribe to our newsletter to not miss any updates, tutorials and tips about SwiftUI and more!

2 replies on “How to embed a SwiftUI view into a UIKit Storyboard”

Very helpful. Please add instructions on how to present and dismiss a SwiftUI View from an Objective-c class.

Leave a Reply

Your email address will not be published. Required fields are marked *

small_c_popup.png

Covid-19 Forces you into quarantine?

Start Mastering swiftUI Today save your 33% discount