Vasily
Vasily

Reputation: 3790

Passing data from modal segue to parent

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.

Upvotes: 12

Views: 9681

Answers (2)

Shashi3456643
Shashi3456643

Reputation: 2041

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)
}

Upvotes: 19

Nerkyator
Nerkyator

Reputation: 3976

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)
}

Upvotes: -1

Related Questions