SwiftUI Views in your existing UIKit Apps
SwiftUI is a powerful UI framework introduced by Apple at WWDC 2019.
SwiftUI lets you write your best apps with as little code as possible. In this tutorial we’ll learn how to integrate SwiftUI views into your already existing UIKit projects. This existing UIKit project can be a storyboard based, programmatic based or even a combination of the two. Let’s get started.
In this starter project we already have an Initial View Controller that has its background color set to red. This simulates a workflow with existing View Controllers.
Click on the “+” on the top right and type in HostingController and drag that out into your main.storyboard file.
Now, we have to make a new SwiftUI file that we’re going to present via this Hosting Controller. For that Cmd + N to create a new file and select a SwiftUI View. For this tutorial we’re going to name this ContentView. Hit Enter and you’ll be presented with some code that represents the SwiftUI View. This code will be enough for this tutorial.
Now we’re going to make the main logic happen.
In your Initial View Controller type in
let swiftUIView = ContentView()
This will create an instance of the newly made SwiftUI View. To present this view from our View Controller we have to import SwiftUI to use the UIHostingController Method.
In the viewDidAppear method inside of your initial ViewContoller type in
let nextView = UIHostingController(rootView: swiftUIView)
present(nextView, animated: true, completion: nil)
This code will present the SwiftUI view from a View Controller! It’s that easy!