Using SwiftUI Previews with UIKit and ObjC

How to live(ish) preview UIKit UI written in Objective C

One of the main selling points of SwiftUI is the live preview feature in Xcode. However, it is also possible to use this new feature with UIKit views, even ones written in Objective C.

Xcode Preview Setup Steps

Starting with a new Objective C Xcode project. Create a new SwiftUI View file.

  1. Accept the creation of the Objective-C bridging header.
  2. Add your UIViewController's to the bridging header.
  3. Replace the SwiftUI view with a SwiftUI UIViewController wrapper.
import SwiftUI

struct VCRepresentable<VCClass:UIViewController>: UIViewControllerRepresentable {
    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
        // leave this empty
    }
    
    @available(iOS 13.0.0, *)
    func makeUIViewController(context: Context) -> UIViewController {
        return VCClass()
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
       VCRepresentable<ViewController>()
    }
}

Xcode won't auto-refresh any changes made outside of the body method, so to refresh you need to press the Resume button or use the keyboard shortcut CMD+ALT+P.

Xcode takes a shortcut to reload a SwiftUI view, but needs to do a rebuild for changes made outside of the views body method (like changes to the ObjC file). Fortunately, if you are using ObjC, the rebuild will be fast so that doesn't matter very much.

For more information on using Xcode Preview's with UIKit in general @soulchildpls's "Use Xcode Previews with UIKit" article goes into more details.

Example Project