user6508243
user6508243

Reputation:

Switching view controllers in swift

I've got 2 view controllers. The main one mainMenuViewController, and the secondary one ViewController.

The secondary view controller has an alert that is sometimes displayed, and when the user selects "Cancel", I want the mainMenuViewController to be displayed.

How can I achieve this with code?

So far I've got the following:

       let refreshAlert = UIAlertController(title: "You Win!", message: "Do you want to play again?", preferredStyle: UIAlertControllerStyle.Alert)

        refreshAlert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: { (action: UIAlertAction!) in
            self.restart()
        }))

        refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in
            print("Handle Cancel Logic here")
        }))

        presentViewController(refreshAlert, animated: true, completion: nil)

When the user clicks Cancel, I've temporarily printed the line print("Handle Cancel Logic here"), but I need the mainMenuViewController to become active.

I've tried creating a function to do this, but it won't work, can you suggest why?

@IBAction func quit(sender: UIBarButtonItem) {
    let vc = mainMenuViewController()
    self.presentViewController(vc, animated: true, completion: nil)
}

Any help appreciated!

Upvotes: 1

Views: 5326

Answers (2)

Lavi Avigdor
Lavi Avigdor

Reputation: 4182

In Swift 3 with Storyboard:

  1. Give your second view-controller a storyboardID. (assuming its called "secondVC")
  2. In the first view-controller's code, when you want to switch, write:

    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let secondVC = storyBoard.instantiateViewController(withIdentifier: "secondVC")
    self.present(mainVC, animated: true, completion: nil)
    

Upvotes: 0

Sweeper
Sweeper

Reputation: 273968

You cannot just call the initializer on a VC class initialize a VC. It is not the correct way to do it.

I assuming you have a storyboard called Main.storyboard. If you don't have one, create one and add the MainViewController. You should give your MainViewController an identifier:

enter image description here

First, you need to get your storyboard:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("mainVC")

Now vc is the MainViewController! You can present it by presentViewController.

Alternatively, you can use segues!

Connect your SecondaryViewController and MainViewController with a segue. Give it an identifier and call

performSegueWithIdentifier("some identifier", sender: self)

Upvotes: 2

Related Questions