1
votes

I'm toying with SwiftUI's access to a UIViewController via the UIViewControllerRepresentable protocol; using a Nib vs instantiating the class manually.

Most of the demo sample I've seen has the ViewController instantiated in code; as shown below:

struct RicViewVC: UIViewControllerRepresentable {
    // Parameters ----------------------------
    // let url: URL
    @Binding var showingVC: Bool
    // ---------------------------------------

    // 1)
    func makeUIViewController(context _: Context) -> RicViewController {
        let viewController = RicViewController()
        Bundle.main.loadNibNamed("RicView", owner: viewController, options: nil)
        return viewController
    }

    // 2)
    func updateUIViewController(_: RicViewController, context _: Context) {}

    // 3
    func makeCoordinator() -> RicViewVC.Coordinator {
        Coordinator(showing: $showingVC)
    }

    class Coordinator: NSObject {
        @Binding var showingCoord: Bool

        init(showing: Binding<Bool>) {
            _showingCoord = showing
        }
    }
}

However this doesn't work when the UIViewController is linked with and IB:

Hello from RicViewController 2020-02-23 10:53:55.893551-0800

SafariRepresentable[9792:151550] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "RicView" nib but the view outlet was not set.'

This is where I'm confused.
How do I link the IB's instantiated XIB into #1 (see above code): makeUIViewController()?
What's the syntax?

2

2 Answers

1
votes

If your RicViewController is XIB owner, then try the following

let viewController = RicViewController(nibName: "_nib_name_here", bundle: nil) // if bundle not main the specify also bundle
return viewController
0
votes

There was a solo UILabel in my UIViewController's View that wasn't referenced. After a trial/error and ref a similar problem on StackOverFlow, I found that I had to:
1) Set the File's Owner to 'RicViewController'; and
2) Set a link between the VC-View's one UILabel to the File's Owner Connection Inspector's 'view'.

enter image description here enter image description here