Oliver
Oliver

Reputation: 33

How to pass data to parent view controller

I'm performing a segue on my parent VC when clicked on an image. I want to pass data back to the parent VC from child VC. I've been exploring various options to pass data back to parent VC but can't figure it out.

Since the child VC is part of Navigation and it's presented (show) via segue there should be an easy way to pass data back to parent.

How to do it?

I've tried viewWillDisappear method but parentVC is nil in following code.

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    if self.isMovingFromParent {
        if let navVC = self.presentingViewController as? UINavigationController {
            if let parentVC = navVC.viewControllers.first as? ParentViewController {
                print("viewWillDisappear() moving to parent") // Not executed
                parentVC.data = self.data
            }
        }
    }
}

Upvotes: 1

Views: 4542

Answers (4)

Kedar Sukerkar
Kedar Sukerkar

Reputation: 1565

Swift 5, Xcode 10.3

Use any 1 of below methods

1.Access reference of parentVC through self.navigationController.viewControllers and then use that reference to access variables and set data

2.you can use unwind segue

3.use delegate protocol

if you need more details, please refer https://stackoverflow.com/a/9736559/10579134

Upvotes: 1

Yoel Jimenez del valle
Yoel Jimenez del valle

Reputation: 1278

You can use 3 ways of assing data back from child to parent ViewController, as mentioned in previos answer you may use delegates, or clousures, but since you dont want to deal with

if segue.identifier == "segueIdentifier"

then you could use notifications, creating observer in the parent and then posting in the child view controller. in the parent

override func viewDidLoad(){
 NotificationCenter.default.addObserver(self, selector: #selector("yourSelectorName"), name: "NotificationName", object: nil)

and in the child post with this.

NotificationCenter.default.post(name: "notificationName", object: nil, userInfo: ["your data array "])

where notification name is not a string you must create a name for it and you may pass data or not in userInfo.

Upvotes: 1

Trupti
Trupti

Reputation: 294

Use delegate for sending data, back to the Parent.

Upvotes: 1

Dancreek
Dancreek

Reputation: 9544

One strategy would be to set the parent as a delegate of the child. You would create this relationship in a prepare(for:sender:) function.

If you are unfamiliar with delegation, this article is a good guide: https://medium.com/@jamesrochabrun/implementing-delegates-in-swift-step-by-step-d3211cbac3ef

Upvotes: 1

Related Questions