SwiftUI

Using Xcode Previews in UIKit Development


When SwiftUI was first released, one of the great features that piqued my interest was the instant preview function. This feature empowers developers to preview the user interface of any view within Xcode, entirely bypassing the need for a simulator.

Prior to Xcode 15, the preview feature was exclusive to the SwiftUI framework. However, with the most recent release of Xcode, Apple expanded the utility of this feature to UIKit as well.

In this tutorial, let’s see how you can make use of this preview feature when developing UIKit apps.

Using #Preview to Preview View Controllers

To preview a UIKit view or view controller in Xcode, all you need to do is set up a preview code block using the #Preview macro. Here is an example:

For those who have experience using the #Preview feature in SwiftUI, the syntax should be quite familiar. Once you input the preview code, Xcode shows an additional pane, providing a preview of your view controller.

uikit-preview-xcode-view-controller

As you change the code of ViewController, Xcode should display the change instantly. For example, you can try to modify the code like below:

The preview pane will show a button that says “Hello”. Like in SwiftUI development, you can check the user interface straight in the preview. If you press the “Hello” button, a warning or alert will pop up.

Xcode-uikit-preview-button-action

Previewing View Controllers in Interface Builder

The #Preview macro can also be used to preview view controllers designed in Interface Builder (or Storyboard). Assuming you’ve created a view controller, configured with a storyboard ID, you can write the following code to preview it in Xcode:

You use the instantiateViewController method to instantiate the view controller and preview it in Xcode. Optionally, you can give the preview a name (e.g. LoginView).

swiftui-uikit-preview-storyboard

Summary

With the release of Xcode 15, Apple has expanded the instant preview feature, previously exclusive to SwiftUI, to UIKit as well. Developers can now preview the user interface of any UIKit view or view controller within Xcode using the #Preview macro, eliminating the need for a simulator. This feature also extends to view controllers designed in Interface Builder or Storyboard. Going forward, make the most of this preview feature to expedite your UIKit development process.

iOS
Building a Text to Speech App Using AVSpeechSynthesizer
iOS
Handling Single and Multiple Selection in Collection View
Tutorial
Building a Trello-like iOS App with Drag & Drop API
There are currently no comments.

Shares