Saturday, June 8, 2019

How to use SwiftUI previews for existing project and storyboard

Here is an example code to create a new swift file for an existing project and use the storyboard Main.storyboard and preview the MainViewController instance in the new iOS 13 SwiftUI framework under Xcode 11.

If you add TabbedView to NavigationView in this example, please use Xcode 11 Beta 2.

MainViewPreviews.swift    Select all
// MainViewPreviews.swift // FishTagCreator // // Created by javacom on 8 Jun 2019. // import SwiftUI #if DEBUG struct MainViewControllerPreviews : PreviewProvider, UIViewControllerRepresentable { // MARK: PreviewProvider static var previews: some View { MainViewControllerPreviews() } // MARK: UIViewControllerRepresentable typealias UIViewControllerType = MainViewController func makeUIViewController( context: Context ) -> MainViewController { let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let mainViewController: MainViewController = mainStoryboard.instantiateViewController(withIdentifier: "MainController") as! MainViewController return mainViewController } func updateUIViewController( _ uiViewController : MainViewController, context: Context) { } } #endif


It is important to assign a storyboard ID say "MainController" to your MainViewController in Main.storyboard's identity inspector.


No comments: