Passing data from modal segue to parent

亡梦爱人 提交于 2019-11-29 01:30:48

问题


I want to pass data (e.g. set var) from modal segue to parent, how can I do that?

I’m using that code to exit from modal segue:

@IBAction func doneClicked(sender: AnyObject) {
    self.dismissViewControllerAnimated(true, completion: nil)
}

I can’t use segue.destinationViewController here to pass data as i’m used to do on push segues.


回答1:


Create protocol on Modal ViewController

protocol ModalViewControllerDelegate
{
    func sendValue(var value : NSString)
}

Also declare in you Modal ViewController class

var delegate:ModalViewControllerDelegate!

Include this protocol ModalViewControllerDelegate in ParentViewController

When you are Moving form one viewController to another

 modalVC.delegate=self;
        self.presentViewController(modalVC, animated: true, completion: nil)

Here you get your value in ParentViewcontroller

 func sendValue(value: NSString) {

    }

Finally on ModalViewController

@IBAction func doneClicked(sender: AnyObject) {
delegate?.sendValue("value")
    self.dismissViewControllerAnimated(true, completion: nil)
}



回答2:


In the second viewController (the one showed by the segue) declare a variable like

var parentVC : UIViewController?

then when you call segue from parent

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
    if segue.identifier == "yourSegue" {
        let secondController= segue.destinationViewController as UIViewController
secondController.parentVC = self
    }
}

so you can use

@IBAction func doneClicked(sender: AnyObject) {
    self.parentVC.yourVariable = 0
    self.dismissViewControllerAnimated(true, completion: nil)
}


来源:https://stackoverflow.com/questions/28502653/passing-data-from-modal-segue-to-parent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!