1

I have three view controllers like below

enter image description here

I wrote the unwind method in viewcontroller1, and try to receive some data from viewcontroller2 and viewcontroller3 when they unwind to viewcontroller1.

@IBAction func unwindToViewController1(segue: UIStoryboardSegue) {
    print("1")
    main_content = (segue.source as! MainContentViewController).main_content
}

@IBAction func unwindToViewController2(segue: UIStoryboardSegue) {
    print("2")
    detailed_content = (segue.source as! SupplementContentViewController).supplement
}

And set the exit unwind segue for both controller 2 and 3 already. enter image description here

But why the unwindToViewController methods never get called correctly? I think they should be called when I click the button automatically created by the system.

button

Patroclus
  • 1,163
  • 13
  • 31

1 Answers1

1

I solve this problem by using delegate instead of unwind. Delegate pattenr is a more explicit way to solve this problem. By creating a protocol called myDelegate

protocol myDelegate {
    func updateMaincontent(main_content : String)
    func updateSupplement(supplement: String)
}

And create a delegate instance inside the second view controller

var delegate: myDelegate?

Then in the first view controller, make the class extend myDelegate and set this delegate of second view controller to self in the func prepare(for segue: UIStoryboardSegue, sender: Any?) method

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destinationViewController = segue.destination as? MainContentViewController {
            destinationViewController.main_content = self.main_content
            destinationViewController.delegate = self
        }
        else if let destinationViewController = segue.destination as? SupplementContentViewController {
            destinationViewController.supplement = self.detailed_content
            destinationViewController.delegate = self
        }
    }

Finally, go back to second view controller, and set the value of delegate to what you want in viewWillDisappear method.

func viewWillDisappear(_ animated: Bool) {
        self.main_content = contentTextView.text
        delegate?.updateMaincontent(main_content: contentTextView.text)
}
Patroclus
  • 1,163
  • 13
  • 31