Swap the Root View Controller

Tram Ho

Development environment:

  • Swift Language Version: Swift 5
  • Xcode: Version 10.2.1 (10E1001)
  • Deployment Target: 12.0

Today I will introduce to you a simple and common way in handling the operation of logging in and out between screens in the iOS App. That’s the Swap the Root View Controller.

Step 1: Initialize the login / main screen

In turn, we will create 2 login and main screens as shown below:

Next we declare loginViewController and mainViewController in the UIStoryboard extension:

Step 2: Create a singleton App class

Here we use UserDefaults to store bool values ​​for the purpose of checking the login / logout of the user.

Step 3: Initialize the switchBackToLogin () and switchLoginToMain ()

The switchBackToLogin () function changes rootViewController = loginViewController when the user presses the logout button at the MainViewController screen.

The switchLoginToMain () function changes rootViewController = mainNavigationController when the user presses the login button at the loginViewController screen.

Step 4: Complete

In AppDelegate.cs , we assign App.shared.window = window and call func startInterface () in singleton App.

In LoginViewController , we set the bool value in UserDefaults to true when the user presses the login button and invokes the switchLoginToMain () function so that the screen switches to MainViewController .

In MainViewController , we set the bool value in UserDefaults to false when the user presses the logout button and calls the switchBackToLogin () function to return to the LoginViewController screen.

And this is the result:

Share the news now

Source : Viblo