简体   繁体   English

iOS / Swift 3:在不连续的View Controller之间向后传递数据

[英]iOS/Swift 3: Passing data backwards between non consecutive View Controllers

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. 我有3个视图控制器和一个导航控制器。 All segues are "show segue". 所有的segues都是“ show segue”。 I would like to pass data from VC3 to VC1. 我想将数据从VC3传递到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. 我的问题是我在源和目的地之间有2个问题。 Your kind help will be appreciated. 您的帮助将不胜感激。

You can use an unwind segue as shown in this Apple Tech Note . 您可以按照本Apple Tech Note中的说明使用轻松的序列。

In your storyboard, create an Unwind segue as shown in the tech note and give it an identifier, say "unwindToVC1" 在情节提要中,按照技术说明中的说明创建一个Unwind segue,并为其指定一个标识符,例如“ 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: 在VC3中,创建一个属性来存储所选值,并在表的didSelectRowAt函数中使用performSegue来调用它,首先将所选值存储在该属性中:

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 VC1创建一个展开动作方法并访问该属性

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. 现在,您可以在当前VC和VC1之间拥有任意数量的视图控制器,并通过简单的放松方式返回到视图控制器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM