How to Pass information Back in iOS when reversing a Segue using Swift?

后端 未结 3 1605
滥情空心
滥情空心 2020-12-09 06:14

I have two view controllers, One and Two. I go from VC One to VC Two. On VC Two, I select some data that I store in an array. When I press the \"Back\" button on the navigat

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 06:41

    If you were presenting a modal view with Done and Cancel buttons (sort of like a picker), grabbing the value during an unwind segue method would probably be the easiest.

    Given that you want to use the navigation controller's native Back button, the best practice would probably be to implement a protocol that VC One can conform to, and then update VC One as soon as the data on VC Two is selected. Something like:

    In VCTwo.swift:

    protocol VCTwoDelegate {
        func updateData(data: String)
    }
    
    class VCTwo : UIViewController {
        var delegate: VCTwoDelegate?
        ...
        @IBAction func choiceMade(sender: AnyObject) {
            // do the things
            self.delegate?.updateData(self.data)
        }
        ...
    }
    

    and in VCOne.swift:

    class VCOne: ViewController {
        ...
        override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
            if segue.identifier == "VCTwoSegue" {
                (segue.destinationViewController as VCTwo).delegate = self
            }
        }
        ...
    }
    
    extension VCOne: VCTwoDelegate {
        func updateData(data: String) {
            self.internalData = data
        }
    }
    

提交回复
热议问题