Unwind segue not transitioning properly

416 views Asked by At

I use a push segue to transition from a uisearchcontroller located within my root view controller, to a second view controller. When I try to use an unwind segue method to transition back to the root view controller from my second view controller, my app does not transition unless the button connected to the unwind method is pressed twice. The unwind method is called both times, however the transition only occurs upon the second call. I do not know why this occurs. Any help is appreciated. Thanks!

Unwind segue method

@IBAction func saveWordAndDefinition(segue:UIStoryboardSegue) {
    self.searchController.active = false
    if let definitionViewController = segue.sourceViewController as? DefinitionViewController {
        saveWordToCoreData(definitionViewController.word)
    }
    tableView.reloadData()
}

How I linked my segue

enter image description here

Unwind segue

enter image description here

2

There are 2 answers

3
kbpontius On

While what you're doing is permissible, it seems to be against best practice. The functionality of presenting a view controller, UITableViewController in this case, entering information, then later dismissing it with a button in the upper-right hand corner is generally associated with a modal view. In a push segue you'll get the back button in the upper-left corner for free, which will enable to you to pop the view controller off the stack without writing extra code.

Here's another Stack Overflow question that describe:
What is the difference between Modal and Push segue in Storyboards?

To answer your question specifically, here are a couple links that should help: [self.navigationController popViewControllerAnimated:YES]; is probably what you're looking for.
Dismiss pushed view from within Navigation Controller
How can I dismiss a pushViewController in iPhone/iPad?

0
user3353890 On

So here's how I finally got this to work:

In my FirstViewController (the vc i'm unwinding to):

Here is my unwind segue method.

@IBAction func saveWordAndDefinition(segue:UIStoryboardSegue) {
    self.navigationController?.popViewControllerAnimated(false)
}

Then I gave my unwind segue the identifier "unwind" in Storyboard.

In my SecondViewController (the vc i'm unwinding from):

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "unwind" {
        if let destination = segue.destinationViewController as? VocabListViewController {
            destination.saveWordToCoreData(word)
            destination.tableView.reloadData()
        }
    }
}

I took care of passing data in the prepareForSegue method of my SecondViewController. Thanks to @Lory Huz for the suggestion. I finally figured out what you meant by it.

Works without any errors!