Skip to main content

Using HostingControllers to integrate SwiftUI in UIKit based projects

Note – This post goes along with this video: https://youtu.be/tmfcllsNvd8

Hosting Controllers are a great way to start integrating SwiftUI into a UIKit based project. It’s very effortless to implement and it allows for an app to use both SwiftUI and UIKit across different parts!

Getting Started

If you haven’t already, you will need to create a SwiftUI view. The easiest way to do this is by going into the menubar in Xcode, File > New > File > SwiftUI View.

You will also need to add a Hosting Controller to your storyboard if you don’t have one already.

Connecting the SwiftUI View

Now that you have a SwiftUI view, we need to connect it to a hosting controller. First, you will need to create a class for the Hosting Controller. (This can be done in the same file as your SwiftUI view)

class HostingView: UIHostingController<ContentView>{

}

Finally, inside your newly created Hosting Controller class, you need some more code to set the root view of the Hosting Controller to your SwiftUI view.

class HostingView: UIHostingController<ContentView>{
   required init?(coder aDecoder: NSCoder) {
      super.init(coder: aDecoder, rootView: ContentView())
   }
}
Note – Make sure to replace “ContentView” with the name of your SwiftUI view

Almost done!

Now that you have completed the Hosting Controller class, all that is left is to set the class of the Hosting Controller in the storyboard to the class that you just created!

Custom Class | Class: HostingView

Full Code

Following is all the code that I used in the video tutorial:

Final Thoughts

Hosting Controllers are a super easy way to start implementing SwiftUI in existing UIKit apps. I’ve already started using these in many of my apps to start moving things to SwiftUI!

If you have any feedback, please leave it in the comments below! If you have any questions regarding this post, you can reach me through my discord server (http://bit.ly/discordvedantapps), YouTube Channel, or through the comments here! Thanks for reading!

Leave a Reply