Home > database >  Can you set the window in the app/scene delegate and still use storyboard?
Can you set the window in the app/scene delegate and still use storyboard?

Time:12-22

I have an app and I am trying to make a simple collectionView. The collectionView works fine if I run from the Main.storyboard using the is initial View Controller.

The problem is when I make my own window using this code:

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    let window = UIWindow(frame: UIScreen.main.bounds)
    window.makeKeyAndVisible()
    window.rootViewController = ViewController()
    self.window = window
    return true
}

and

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

var window: UIWindow?


func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }
    let window = UIWindow(windowScene: windowScene)
    window.makeKeyAndVisible()
    window.rootViewController = ViewController()
}

I get this error on my collectionView code:

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

Question:

Is there a way to create your own UIWindow and still use storyboard?

P.S if you are wondering why I don't just use storyboard instead of making my own UIWIndow it's because I already have my app created completely programmatically and I just need to use storyboard this one time to make self sizing UICollectionViewCells. I couldn't figure out how to do it programmatically, but I have it figured out on storyboard.

CodePudding user response:

Set your root view controller either from SceneDelegate or from App Delegate or from the Storyboard, you don't have to do it in all the places.

If you are just trying to initialize your ViewController from code you don't need any storyboard and the initializer you called ViewController() does not instantiate a view controller from the storyboard. to know how you can instantiate a view controller associated with a storyboard please refer to this link.

You can use any view controller as a root view controller it depends on you.

isInitialViewController sets that view controller as the root view controller of the window.

If you just want to use your ViewController as the root view controller which you already codded in the app delegate, now just delete the storyboard and its references from info.plist file then you are good to go.

  • Related