Integrating UIKit in SwiftUI

Eniela P. Vela
Swift Blondie
Published in
4 min readOct 12, 2021

--

There will be time when as a developer you’ll have to use UIKit in SwiftUI. Some of you might ask why do we need to integrate UIKit when SwiftUI is already advanced and offers a variety of design kit. There are cases that you might have an existing UIKit and you don’t have time to update it or you won’t want to update it. Whether it’s an existing View or your custom view, it can be done. Plus, any existing constraints are respected.

In this article we will incorporate UIKit in SwiftUI step by step. Do not miss any step as you’ll be required to go back.

UIViewRepresentable

SwiftUI provides a protocol specifically for including UIView instances into your code. Basically, we’re going to create a View struct that returns a UIView class.
The UIViewRepresentable protocol inherits from View. However, it specifies it to be a View that doesn’t implement the body computed property. So it’s a View but not like we’ve seen before.
Instead the protocol defines a function to be implemented. The makeUIView function UIKit classes into SwiftUI needs to return a UIView. Simple.
It’s also passed in a Context for any values you might need to retrieve.
When the state changes and it’s time to update the UI, there’s another function: updateUIView. This function is called when there are changes in any bindings. In the function code, you will update the UI…

--

--

Eniela P. Vela
Swift Blondie

iOS Developer | Technical Writer | Software Developer @ Apple