Live Preview UIKit in Swift

Inspect an UIViewController without running the project

Tolga Taner
2 min readMar 7, 2022


Photo by Paul Skorupskas on Unsplash

Preview is a cool feature that comes with SwiftUI to show views in xCode without any running operation so, what if UIKit? For example, If you want to do same thing for UIKit to minimize service request count when drawing, coding some complex UI, you are bored about endless Xcode builds, The answer is why not? Let’s look at closely.

Let’s create a class named ViewControllerPreviewer that conformed ViewControllerRepresentable. It contains a view controller to show it inside preview. ViewControllerPresentable wants a typealias to define type of which UI element showed. It is defined asDEBUG build configuration scope for the optimization. This preprocessor macro checking runs this code inside debug. We don’t need it for release or other user-defined build configurations.

It has two functions that must be conformed, one of them is useless for this case, we will use just

func makeUIViewController(context: Context) -> UIViewController

This returns our builder closure.

After creating previewer completely, let’s look at the view controller part. We only change the background color of view controller’s view.

To do that, let’s create ViewController_Previews that is running for iPhone X. It immediately shows a preview screen at right part of previewing View Controller.

As we expect, we saw preview for a view controller to write a new representer. It made a lot of work easier.