Search code examples
iosswift3uinavigationcontrollerpushviewcontroller

pushing the new view controller (programatically) doesnt work ? why?


enter image description hereHere I am in a viewController and I want to go to another viewController with id of ViewUSRControllerID here is my code . The objective to move after I the user logged in :

@IBAction func login_btn(_ sender: UIButton) {
    if username_txt.text == "" || password_txt.text == "" {

        //print("empty")

        let alert = UIAlertController(title: "Error", message: "you must fill up both username and password", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil))
        self.present(alert, animated: true, completion: nil)

    }else if (username_txt.text! == "admin" && password_txt.text! == "Passw0rd" ){

             print("login successful")

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let cr = storyboard.instantiateViewController(withIdentifier: "ViewUSRControllerID")
        self.navigationController?.pushViewController(cr, animated: true)


        }
    }

The output is that I can print the login successful but no pushing is being made . For the sake of testing I replaced :

self.navigationController?.pushViewController(cr, animated: true)

with : self.present(cr, animated: true)

at it works fine . But why the pushing doesnt work ?


Solution

  • In your code self.navigationController?.pushViewController(cr, animated: true)

    self.navigationController? is optional property of UIViewController if your LoginViewController is embedded With UINavigationController than you can use UINavigationController method pushViewController and this method push ViewUSRController from LoginViewController.

    So if you are using storyboard than it's very simple to embedded UINavigationController in LoginViewController.

    Steps :-

    1.Select LoginViewController in storyboard. 2.xCpode top panel "Editor" 3.Select "Embed in" -> UINavigationController

    It's looks like this

    enter image description here