Open Xcode Live Preview for UIKit

One of the big benefits of using SwiftUI is that you can hot update the App like Flutter,UI code changed,Will be directly reflected in the simulator or the real machine,Greatly improve the efficiency of writing user interfaces,No need to change 1px,run,Various clicks,Then check the loop of effects。But it's too early to use SwiftUI,After all, there is still a lot of iOS 12 Equipment is running,Want to do popular software,That still needs to be supported。

Then,Is there any way to make UIKit Can the written software also use real-time preview? It's actually possible... after all,SwiftUI can also directly display UIKit controls。

First of all, let’s take a look at Xcode Preview SwiftUI,What needs to be done:

You only need to be in any one .swift Add the above code to the file,Xcode will show you the preview interface,To make it load UIKit,We need to implement a UIViewControllerRepresentable / UIViewRepresentable ,It depends on what you want to display UIViewController still is UIView

These two structures are common,So that it can be used directly in the future。But there is a problem,When we actually compile,You need to modify the minimum supported version number,Because after all, it relies on SwiftUI,This leads to the need to increase the version number during development,Lower it when it is officially released。

We can use Swift macros to do this,Such,The compiler can automatically determine whether SwiftUI is currently supported,And when it is officially released,Will automatically remove these codes。

Have written these two Representable after that,We go to the file that needs to be previewed,Enable preview:

Such,Xcode can preview your interface just like using SwiftUI! No matter what is modified,All can be displayed in the side preview in real time!

note,If you use a script that automatically increases the version number after each compilation,That may cause the preview to not refresh automatically,Manually click Resume every time,such as:

version= expr $version + 1
/usr/libexec/PlistBuddy -c “Set :CFBundleVersion $version” $PRODUCT_SETTINGS_PATH[/crayon]
We need to modify them to identify Live Preview mode:

version= expr $version + 1
/usr/libexec/PlistBuddy -c “Set :CFBundleVersion $version” $PRODUCT_SETTINGS_PATH
echo “Skipping the script because of preview mode”
Such,The script will only be executed during normal compilation,Will not affect Xcode Live Preview。



  1. How to Use Live Previews in UIKit
  2. /UIViewPreviewProvider
  3. SwiftUI: Automatic preview updating paused, always


Original article written by Gerber drop-off:R0uter's Blog » Open Xcode Live Preview for UIKit

Reproduced Please keep the source and description link:

About the Author


The non-declaration,I have written articles are original,Reproduced, please indicate the link on this page and my name。

Leave a Reply

Your email address will not be published. Required fields are marked *