0
votes

I know there are answers for passing data backwards, but they are for consecutive view controllers. I have 3 view controllers and a navigation controller. All segues are "show segue". I would like to pass data from VC3 to VC1. I'm trying to use delegate, but getting stuck:

    protocol Delegate:class {
        func getCityId(with id: String)
    }


    Class VC3:UIViewController{
     weak var delegate: Delegate?
    let id:String?

     func passDataBackwards() {

            delegate?.getCityId(with: self.id!)

    }

  }  
    Class VC1:UIViewController, Delegate{
     func getCityId(with id: String) {
            print ("id from search: \(id)")

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc3 = (segue.destination as! VC3)
          vc3.delegate = self
       }
   }

My problem is that I have 2 segues between my source and destination. Your kind help will be appreciated.

1
An unwind segue is all you needPaulw11
So it can't be done using delegate? My VC3 has a table view. Whenever I click on a cell, I want to move to VC1 and pass data to it. I'm not sure how I can do it with unwind.benh
You could use a delegate but it is messier. You need to define the protocol and pass the delegate "down the line" through view controllers that don't need it. By using an unwind method, VC1 can access the sourceViewController property of the storyboard segue passed its unwind method to get a reference to VC3. It can then read the required data from a property of vc3Paulw11
Thank you, Paul. How can I connect a table view cell to the exit? @Paulw11benh

1 Answers

0
votes

You can use an unwind segue as shown in this Apple Tech Note.

In your storyboard, create an Unwind segue as shown in the tech note and give it an identifier, say "unwindToVC1"

In VC3, create a property to store the selected value and use performSegue in your table's didSelectRowAt function to invoke it, having first stored the selected value in the property:

class VC3: UIViewController {

   var selectedValue: YourValueType?

   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       self.selectedValue = myData[indexPath.row]
       self.performSegue(withIdentifier: "unwindToVC1", sender: self)
    }
}

Create an unwind action method in VC1 and access the property

class VC1: UIViewController {

    @IBAction func unwind(sender: UIStoryboardSegue) {
        if let sourceVC = sender.sourceViewController as? VC3 {
            if let selectedValue = sourceVC.selectedValue {
                // Do something with the selected value
            }
        }
    }
}

Now you can have any number of view controllers between the current VC and VC1 and get back to it with a simple unwind segue.