move to next view controller programmatically

There are multiple ways how you create your login page UIViewController:

  1. From xib, for example, you can inherit your controller from this class:
class XibLoadedVC: UIViewController {
        required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
        required init() {
            print("init \(type(of: self))")
            let bundle = Bundle(for: type(of: self))
            super.init(nibName: String(describing: type(of: self)), bundle: bundle)
        }
    }

or just

let controller = LoginPageViewController(nibName: "LoginPageViewController", bundle: nil)
  1. From storyboard:
let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
let loginPage = storyboard.instantiateViewControllerWithIdentifier("LoginPageViewController") as! LoginPageViewController

There are multiple ways to show controller depending on how you are create it:

  1. You can just present controller with:
func tapActionButton(sender: UIButton!) {
    let loginPage = LoginPageViewController()
    self.present(loginPage, animated: true)
}
  1. Programmatically push using navigationController:
navigationController?.pushViewController(loginPage, animated: true)

Requires UINavigationController to work. As you can’t be sure, is your controller inside navigation controller stack or not, there is optional navigationController? to not crush the app :)

  1. Storyboard and Segues:

Create segue between your ViewController and LoginPageViewController. Give your segue an identifier and also presentation style. For this case it will be Show Example

Now in your ViewController override below method

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
   if segue.identifier == "YourSegueIdentifier"
       let loginPage = segue.destinationViewController as! LoginPageViewController
   }
}

On loginButton tap action:

func tapActionButton(sender: UIButton!) {
    performSegueWithIdentifier("YourSegueIdentifier", sender: nil)
}

And you are done.

P.S. Also, there is modern SwiftUI way to do all that, you can look into tutorials and official documentation.


You need to create an instance of the next view controller and then either present or push that view controller

To present modally:

self.presentViewController(nextVC, animated: true, completion: nil)

or to push:

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

all that stuff with segues apply to storyboards

Cheers!

Tags:

Uibutton

Swift