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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.