Search code examples
iosswiftswiftuistoryboarduihostingcontroller

SwiftUI in Storyboard Project Comes Up Blank


I'm following this tutorial:

https://www.youtube.com/watch?v=aWL7W8SLfeo

...on importing a SwiftUI file into an existing Storyboard project. When it didn't work in my existing project I made a brand new one from scratch (Xcode 13.2.1) and it doesn't seem to matter. When I click the link to go to the ViewController hosting the view... it still comes up blank.

The Hosting ViewController:

import UIKit
import SwiftUI

class PokeViewController: UIViewController {

    @IBOutlet weak var theContainer: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let childView = UIHostingController(rootView: SwiftUIView())
        addChild(childView)
        theContainer.addSubview(childView.view)
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

The SwiftUI:

import SwiftUI

struct SwiftUIView: View {
    var body: some View {
        Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }
}

Here's the AppDelegate and SceneDelegate if that helps:

import UIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {



    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }


}

SceneDelegate

import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        guard let _ = (scene as? UIWindowScene) else { return }
    }

    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    }

    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
    }

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
    }


}

The PokeViewController class is connected to the correct ViewController in the storyboard... and the SwiftUIView is connected to the view. But when I visit PokeViewController... it's just blank (though I KNOW any code I have is being run. If I do something like an ImagePicker and set its default launch to "True"... it launches... and I can see the images... but once I'm done or click cancel it's back to the same blank page.)

Any help would be appreciated.


Solution

  • Try to add after

    theContainer.addSubview(childView.view)
    

    following code:

    childView.view.translatesAutoresizingMaskIntoConstraints = false
    let constraints = [
        childView.view.topAnchor.constraint(equalTo: theContainer.topAnchor),
        childView.view.leftAnchor.constraint(equalTo: theContainer.leftAnchor),
        theContainer.bottomAnchor.constraint(equalTo: childView.view.bottomAnchor),
        theContainer.rightAnchor.constraint(equalTo: childView.view.rightAnchor)
    ]
    
    NSLayoutConstraint.activate(constraints)
    
    /// Notify the hosting controller that it has been moved to the current view controller.
    childView.didMove(toParent: self)
    

    There is an extension:

     extension UIViewController {
    
        /// Add a SwiftUI `View` as a child of the input `UIView`.
        /// - Parameters:
        ///   - swiftUIView: The SwiftUI `View` to add as a child.
        ///   - view: The `UIView` instance to which the view should be added.
        func addSwiftUIbodyView<Content>(_ swiftUIView: Content, to view: UIView) where Content: View {
            let hostingController = UIHostingController(rootView: swiftUIView)
    
            /// Add as a child of the current view controller.
            addChild(hostingController)
    
            /// Add the SwiftUI view to the view controller view hierarchy.
            view.addSubview(hostingController.view)
    
            /// Setup the contraints to update the SwiftUI view boundaries.
            hostingController.view.translatesAutoresizingMaskIntoConstraints = false
            let constraints = [
                hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
                hostingController.view.leftAnchor.constraint(equalTo: view.leftAnchor),
                view.bottomAnchor.constraint(equalTo: hostingController.view.bottomAnchor),
                view.rightAnchor.constraint(equalTo: hostingController.view.rightAnchor)
            ]
    
            NSLayoutConstraint.activate(constraints)
    
            /// Notify the hosting controller that it has been moved to the current view controller.
            hostingController.didMove(toParent: self)
        }
    
     }