Embed Navigation Controller from code (Not Storyboard)

So far you have noticed, we embed the Navigation Controller using the Storyboard (refer to 3.1. Navigation Controller and UI setup ). What about we want to remove that process and want to add Navigation Controller by writing code? That way it'll be easy to change the name of the default "ViewController.swift" file to a more appropriate name.

To start, we will create a new iOS project in Xcode named, "NavConFromCode."

We already know that it comes with a default view controller: ViewController.swift

So let's first change the name of it to a different name: FirstScreenViewController.swift

Please note, we are also changing the name of the class.

Then just open SceneDelegate.swift file, and update the func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) function.

On line 3, we define windowScene as a variable since we want to manipulate the window on the app.

On line 6, we define our root view controller for the navigation stack. (Our first/main screen).

On line 9, we define the navigation controller to be added. And set the root view controller to the main screen.

Then on lines 14 through 16, we setup the window of the app.

Now, if we run the app, it should run as the FirstScreenViewController being the main view controller.

Deleting the Main.storyboard

  1. Delete the storyboard file from file explorer.

  2. Open project's Info.plist

    1. Select your project in the Project Navigator

    2. Select your app target

    3. Go to the "Info" tab

    4. Expand "Application Scene Manifest"

    5. Expand "Scene Configuration"

    6. Expand "Application Session Role"

    7. Expand "Item 0"

    8. Delete the row: "Storyboard Name" (value: "Main")

    9. Find "Main storyboard file base name" or "Main Interface". Delete the value (set it to empty)

Resource Files

26KB
Open

Last updated

Was this helpful?