UIKit in SwiftUI framework & SwiftUI in UIKit

Imad Ali Mohammad
3 min readJul 25, 2022

The SwiftUI framework was unveiled in 2019 and in just a few years has proven to be impactful in the developer community. But it is also true that UIKit has been around since 2008! Especially if you have been a developer for a few years you will have Apps developed using UIKit. Why not use all that SwiftUI offers to give your apps a makeover in UIKit apps & vice-versa. Let’s discuss those using an example.

1. UIKit in SwiftUI

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

UIViewRepresentable

A view that represents a UIKit view. Use this when you want to use UIView inside SwiftUI.

To make any UIView usable in SwiftUI, create a wrapper view that conforms UIViewRepresentable.

Now let’s create an ActivityIndicator (or you can customize any UIKit control) that extends the UIViewRepresentable

Now let’s use this in your SwiftUI file as:

Excellent! Now you’ve used UIKit in your SwiftUI file.

2. UIKit in SwiftUI

Given the benefits of using SwiftUI for future development, it will be a common requirement to integrate the new SwiftUI app functionality with the existing project codebase. Fortunately, this integration can be achieved easily using UIHostingController

UIHostingController

A UIViewController that represents a SwiftUI view.

The hosting controller is compatible with UIKit since it is a subclass of UIViewController. The purpose of the UIHostingController is to enclose a SwiftUI view so that it can be integrated into an existing UIKit-based project.

Suppose you have got an existing SwiftUI file (let’s name it as ‘ContentView.swift’)in your project then you want to load it in your UIViewController class.

You can also pass SwiftUI controls to UIHostingController as:

Note: Both features requires iOS 13.0+

Hurrah!!! Now you can seemingly use both frameworks inside your project. Hope you like it.

--

--

Imad Ali Mohammad

Senior iOS Engineer, Passionate about coding and building amazing apps.