Jones
Jones

Reputation: 23

UIViewController setting new root view when click button

I have this code for a button that when clicked takes the user to the home page which is a UIViewController I have named 'HomePageViewController', I have also set the class as seen: class set up.

The button code is located in the first (initial controller) UIViewController called 'SignInViewController', when it is clicked I want the HomePageViewController to replace the SignInViewController:

  @IBAction func btnSignInPressed(_ sender: UIButton) {
        // if true take to home page
        DispatchQueue.main.async {
            let home = self.storyboard?.instantiateViewController(identifier: "HomePageViewController") as!
            HomePageViewController
            
            // replace the homepage as the root page
            let appDelegate = UIApplication.shared.delegate
            appDelegate?.window??.rootViewController = home
        }
    }

However, when I run this in stimulator, the button does not do anything, when I click it. Just a note, I am using a Tab Bar Controller, so I tried setting the root to the UIBarController, however this also did not work.

Upvotes: 1

Views: 620

Answers (1)

Tomo Norbert
Tomo Norbert

Reputation: 780

In your appDelegate, add property:

final var window: UIWindow?

Call it like this

@IBAction func btnSignInPressed(_ sender: UIButton) {
    // if true take to home page
    DispatchQueue.main.async {
        let home = self.storyboard?.instantiateViewController(identifier: "HomePageViewController") as!
            HomePageViewController

        let window = UIApplication.shared.delegate!.window!!
        window.rootViewController = nil
        window.rootViewController = home
        
        UIView.transition(with: window, duration: 0.4, options: [.transitionCrossDissolve], animations: nil, completion: nil)
    }
}

Upvotes: 3

Related Questions