SwiftUI Views in your existing UIKit Apps

Swapnanil Dhol
2 min readSep 12, 2019

--

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.

This is how your project should look like now.

Click on the “+” on the top right and type in HostingController and drag that out into your main.storyboard file.

Your Main.storyboard file should now look like this.

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.

ContentView.swift

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!

The only way I can afford the new iPhones: using them in the new Xcode simulators.

--

--

Swapnanil Dhol
Swapnanil Dhol

Written by Swapnanil Dhol

•23 • 3x WWDC Scholar •GSoC 2020 with VLC •iOS Engineer •Airplane and Space Enthusiast

No responses yet