user1457381
user1457381

Reputation:

Switching Back & Forth Between View Controllers Swift

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
    }

Upvotes: 0

Views: 1277

Answers (3)

Chameleon
Chameleon

Reputation: 1608

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()

Upvotes: 1

Abdullah
Abdullah

Reputation: 7233

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.

Upvotes: 1

chirag90
chirag90

Reputation: 2240

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

Upvotes: 0

Related Questions