SWIFT UI PREVIEW FOR UIVIEW

How to use SwiftUI preview with UIView

Avoid some runs on simulator or device to make UI

Jonathan Mercandalli
by MWM

--

Even if you do not want to convert your views to SwiftUI, you can use the Xcode preview of SwiftUI with UIView đź‘€

1. UIView example

Here a HelloWorld custom view displaying a UILabel with “HelloWorld” like the screenshot above.

2. PreviewProvider

In order to use SwiftUI to display the Xcode preview, add the SwiftUI import.

Then, implement
- UIViewRepresentable for UIView
-
UIViewControllerRepresentable for UIViewController

Finally, add a struct PreviewProvider to your class and tada 🎉
Opening the swift file in Xcode opens the preview.

3. Tips to go further

  • [Preview resize]
    Inside the Preview struct, implement sizeThatFits.
  • [PreviewMode]
    UIView will run on Xcode.
    Means the AppDelegate.applicationDidBecomeActive and other iOS lifecycle methods will not be called.
    So, some static fields or instances may not be reachable in preview mode.
    Proposition: provide a boolean to the UIView to use mocks for the preview.
  • [Crash]
    I didn’t find a way to get stacktrace when UIView is crashing in the preview mode.
  • [Update preview]
    Close / Re-open the file reload the preview.
  • [Show / Hide]
    Toggle via: Xcode menu > Editor > Canvas

Do not hesitate to comment if you have any idea to improve this article. (As an Android dev, iOS dev is pretty new for me ^^)

Source: Thank you to Finsi Ennes article

--

--

Jonathan Mercandalli
by MWM
Editor for

Android Lead at MWM. Android is my passion. More about me on mercandalli.com