Use SwiftUI in UIKit Projects

Hazarath Reddy
3 min readMay 2, 2022

--

SwiftUI is a declarative programming language. It helps to build great apps for multiple apple products.

Building projects with SwiftUI is really amazing. But it’s runs on iOS 13, macOS 10.15, tvOS 13, and watchOS 6, or any future later versions of those platforms.

SwiftUI works seamlessly with the existing UI frameworks on all Apple platforms. Like, you can place UIKit views and view controllers inside SwiftUI views, and vice versa.

Apple provides a great strength and flexibility to integrate SwiftUI with UIKit and AppKit

Let’s integrate SwiftUI into UIKit project

Follow the steps to create a UIKit project

Step 1: Open Xcode and create a new project

Step 2: Choose the interface type as Storyboard

Step 3: Click on next and create project

UIKit projects allows you to create a new SwiftUI files as well. Go ahead and create a new SwiftUI file in same project

MainContentView is a swiftUI file with simple code base to show alert on button click.

It’s time to use SwiftUI file in UIViewController file. Before get into this, let understand about UIHostingController

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.

UIHostingController allows you to create an instance of SwiftUI file

Let’s create an instance of MainContentView in UIViewController file

let hostingFile = UIHostingController(rootView: MainContentView())

Add hostingFile to UIViewController as a subview and set constraints to hostingFile view.

That’s it. Run your project and can see SwiftUI file changes in UIViewController file

Hope you enjoyed the article and thank you for reading..

--

--