Using SwiftUI from UIKit

Mateus Kamoei
2 min readAug 7, 2020

--

So when SwiftUI first came out you jumped right into it. You couldn't wait to leave storyboards behind. You learned everything there is to know about state variables and binding. Unfortunately you landed on a project that still uses UIKit. What do you do? Forget everything you have learned and go back to constraints and auto layout? No! Let's see how we can interface UIKit and SwiftUI.

UIHostingController is here to help you

The component that allows us to do this integration is called UIHostingController. Apple docs states:

Create a UIHostingController object when you want to integrate SwiftUI views into a UIKit view hierarchy. At creation time, specify the SwiftUI view you want to use as the root view for this view controller; you can change that view later using the rootView property. Use the hosting controller like you would any other view controller, by presenting it or embedding it as a child view controller in your interface.

In the sample project we have a simple table view made using UIKit that presents a simple list of movies. When tapping a movie we want to present a SwiftUI detail screen showing its cast and genres. We also want to be able to favorite the movie in this detail screen. We are going to do just that on our table view's tableView:didSelectRowAt: method. See the sample below which was taken from the test project.

In the code above movieDetail is our SwiftUI view. All we need to do is instantiate it and pass it as the root view of our UIHostingController. We are also adding to it the movie we want to display in the detail view as an environment object. Pretty simple, uh?

SwiftUI to UIKit

What about comunicating back to our UIKit table view controller? If you are paying close attention you may have noticed in the code above that we are also setting a delegate and an index path of our MovieDetail class. We will use those to reload the movie we have favorited on our movies list.

This is the code for the favorite button in our MovieDetail swiftUI class. When pressed it will toggle the movie favorite status and also call the didSetFavorite method of our delegate to update the appropriate row on our movie list. Here is the implementation of that method:

That's pretty much it. Here we took a quick look on how to use SwiftUI from UIKit and how to comunicate back and forth between them. The full project can be downloaded at https://github.com/mateus-kobe/uikit-swiftui.

--

--