Search code examples
iosswiftxcodeswiftuipreview

Views from storyboards won't appear in Xcode Preview


I try to use Xcode Preview feature. It works well when I add views directly in code, but if I add any views via storyboard, preview won't show these views. Here is my code:

import UIKit

final class ViewController: UIViewController {

    @IBOutlet weak var segmentedControl: UISegmentedControl?
}

#if canImport(SwiftUI) && DEBUG
import SwiftUI
struct ViewControllerRepresentable: UIViewRepresentable {

    func makeUIView(context: Context) -> UIView {
        return ViewController().view
    }

    func updateUIView(_ view: UIView, context: Context) {

    }
}

@available(iOS 13.0, *)
struct ViewController_Preview: PreviewProvider {

    static var previews: some View {
        Group {
            ViewControllerRepresentable()
        }
    }
}

#endif

That's my controller in simulator and storyboard:

enter image description here

That's how this controller looks in preview:

enter image description here


Solution

  • Set storyboardID (for example "ViewController") for your ViewController in storyboard.

    enter image description here

    Then create viewController from storyboard

    func makeUIView(context: Context) -> UIView {
        let viewController = UIStoryboard(name: "Main", bundle: nil)
            .instantiateViewController(withIdentifier: "ViewController")
        return viewController.view
    }
    

    Use your storyboard name instead of "Main" if it's different.