0

I don't know why but I'm having so much trouble trying to figure out how to go back to the main view. I use the code below to switch to the new view but how do I go back?

@IBAction func printPage(sender: AnyObject) {
        var vc = self.storyboard?.instantiateViewControllerWithIdentifier("labelView") as PrintLabelView
        self.presentViewController(vc, animated: true, completion: nil)
        vc.toPass = skuLabel.text
    }

3 Answers3

1

As you are presenting a UIViewController you should have some back button in the presented UIViewController by clicking it user is able to go back.

In the IBAction of that button you could have following code:

@IBAction func goBack() {
    dismissViewControllerAnimated(true, completion:nil)
}

If you are using navigation view controller the functionality by default is provided by it.

Abdullah
  • 6,605
  • 6
  • 23
  • 39
  • This did it. Thank you! I remember using this back then but I thought for some reason it didn't work anymore. –  Mar 25 '15 at 16:38
1

Use Unwind.

In MainViewController

@IBAction unwindSegue(segue: UIStoryboardSegue, sender: UIStoryboardSegue){//any code you want executed upon return to mainVC
}

In NewViewController

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){//pass any information from New to Main here
}

Then, in NewVC, simply control+drag from whichever UIButton you want to cause the unwind to NewVC's Exit symbol and select unwindSegue

*

*

NOTE: Also if you want the unwind to happen programmatically instead of from a Button. enter image description here Control+drag from NewVC yellow to exit, this will create an unwind segue under "Exit"enter image description here Select this "Unwind segue" and in attributes inspector give it an identifier.enter image description here

Now in NewVC create a function

func NameYourFunc(){performSegueWithIdentifier("TheIdentiferYouUsed", sender: self)}

and anywhere in your NewVC code when you want to perform this unwind simply call NameYourFunc()

Chameleon
  • 1,516
  • 2
  • 20
  • 35
0

I have had similar issue before where i found it difficult to go back, 1st thing which i didnt have was navigation controller and required the below code

func goToMainVC() {
    if let navController = self.navigationController {
        navController.popToRootViewControllerAnimated(true)
    }
}

Please look at the answer which was posted when i had similar issue here

Hope fully this will help

Community
  • 1
  • 1
chirag90
  • 2,061
  • 1
  • 19
  • 34