1

When I press the back button in this navigation controller, I want to send the state of the switches to variables in a different View Controller. However, the prepareForSegue method is not being called. How do I fix this?

enter image description here

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print("here")
    let secondViewController:ViewController2 = segue.destination as! ViewController2

    if undoSwitch.isOn {
        secondViewController.undoControls[0] = true
    }
    else {
     secondViewController.undoControls[0] = false
    }
}
Chris
  • 2,435
  • 6
  • 26
  • 49

3 Answers3

0

The back button is different from segue. If you want to reload the undoSwitch when going back from the current view controller. One of the ways is to use a static global variable. Something like

class AppVar {
    static var controlState = true
}

Update your AppVar.controlState where you need and add this

if AppVar.controlState {
    secondViewController.undoControls[0] = true
}
else {
     secondViewController.undoControls[0] = false
}

to viewWillAppear of the ViewController2 as the ViewController2 was retained and stored in stack. When you navigate back to it, the viewWillAppear will be called.

Lawliet
  • 3,438
  • 2
  • 17
  • 28
0

Rewrite your self.navigationItem.leftBarButtonItem, add an action to it, and do whatever you want. Or use https://github.com/onegray/UIViewController-BackButtonHandler

Andy Darwin
  • 478
  • 5
  • 19
0

If you want to send data from ViewControllerA to ViewControllerB you can pass data using prepare for segue method or instantiating ViewControllerB storyboard id and access its properties and pass data.

If you want to do vice-versa i.e. passing data back from ViewControllerB to ViewControllerA, you can use various patterns. Delegation , Notification , Kvo or using NSUserDefaults.

In your case Delegation Pattern will be best. Assign ViewController2 as delegate of your current class. And pass data(in your case control state) using protocols of your current class. Implement the protocol in ViewController2 and access control state of your switches and do accordingly. You can refer my previous ans on this topic.Look here for my detailed ans in Objective-C. Hope it helps. Hapy Coding!!

luckyShubhra
  • 2,731
  • 1
  • 12
  • 19
  • I think I have a better solution. I just moved the variable undoControls outside of the class. Now, I can easily access it wherever I need it since it is public. Is there any reason why this would not be a good idea? – David Ruvinskiy Jul 04 '17 at 12:46