How to Use Live Previews in UIKit
Avoid endless Xcode builds on your UIKit projects

SwiftUI has changed the way of writing UI code but let’s be honest, most of iOS apps still use UIKit as framework. Migration to SwiftUI will be slow but meanwhile we can use some of its amazing tools, such as Live Previews.
In this tutorial you will learn how to wrap UIViewController
and UIView
into SwiftUI views in order to use Live Previews. Result will be the following:

Preview for UIViewController
If we want to add an UIViewController
object into a SwiftUI interface, then we are going to need the UIViewControllerRepresentable
protocol.
Start by creating a SwiftUI view that conforms such protocol:
Our struct will accept () -> UIViewController
as closure:
- This is a key aspect because it provides us a generic solution. We will be able to use any of our view controller instead a particular one.
Now, we have to add the requirements for UIViewControllerRepresentable
:
- The
makeUIViewController
method will return the initial view controller. SwiftUI calls this method once, this is when it’s ready to display the view. Then manages the view controller’s life cycle. - The
updateUIViewController
method is called for any changes affecting the corresponding. In our case, the view controller doesn’t depend on the state changes, so we leave it empty.
At this point we are ready to use the ViewControllerPreview
. Thus, let’s implement a simple view controller to test this feature.
In this example, we are going to create a UIViewController
that contains a centered image. We’ll retrieve several symbol images to show how Live Preview works on this context:
Create the PreviewViewController
using the following code:
Finally, use the ViewControllerPreview
inside a PreviewProvider
:
We are done:

Preview for UIView
Once we know how to deal with UIViewController
, work with UIView
is really straightforward. Solution looks like:
References
Special thanks to Alexandre Freire:
Rest of references: