Passing Data From SwiftUI To a UIKit View Controller

Daily Coding Tip 042

Most of the time, when we talk about combining UIKit and SwiftUI, we talk about UIViewRepresentable. This gives us the ability to reuse a UIView, which is especially useful when SwiftUI doesn’t include the same controls as UIKit. But it’s possible to use an entire view controller (VC), which means that SwiftUI can act as the host for any number of UIKit-based animations and interfaces, as well as the logic that makes them work.

First we’ll create a simple UIViewController subclass that adds a label and constrains it to the middle of the screen.

Now we can add our UIViewControllerRepresentable structure. The makeUIViewController and updateUIViewController functions are much the same as they would be in UIViewRepresentable. The first is called only once to create the VC, then the other is called whenever the SwiftUI is updated so that it can pass data. The difference is here is that a VC probably has a lot more internal logic than the typical UIView would have.

Because we have a Binding to a string set by a SwiftUI TextField, our updateUIViewController function will be called when the user makes changes. Despite the fact that the VC has no logic of its own for setting the label text as a result of the TextField input being changed, we set the label as a public property. Our UIKitVC can therefore make whatever changes it wants, but it’s easy to see how this could call a function instead, keeping the properties of the VC private.

Get more Daily Coding Tips in your inbox!