Greg Peckory
Greg Peckory

Reputation: 8048

Accessing parent view from modal segue Swift

I have a View Controller - NewsController which has a modal segue going to NewsDetailController

In NewsDetailController I am trying to run the following function:

@IBAction func greenLikeClick(sender: AnyObject) {

    if let parentVC = self.parentViewController as? NewsController {
        parentVC.newslists[loadsection][loadrow].liked = false
    }
}

But this won't work.

Is there a parent-child relationship going on between NewsController and NewsDetailController here?

If so, why isn't my approach working?

If not, how would I approach this?

Upvotes: 3

Views: 7922

Answers (2)

Mehrdad Dehghani
Mehrdad Dehghani

Reputation: 677

I did it like this for when my segue was pushed:

if let presenter = self.navigationController?.viewControllers[0] as? MainViewController {
        // access presenters members

}

and like this for when my segue was presented:

if let presenter = self.presentingViewController?.children[0] as? MainViewController  {
        // access presenters members
}

You should manage the children or viewcontrollers index if you have more than one. mine was single so 0 did the trick.

Upvotes: 1

HHK
HHK

Reputation: 1412

You should use self.presentingViewController in your NewsDetailControllerto get your NewsController. From the documentation:

When you present a view controller modally (either explicitly or implicitly) using the presentViewController:animated:completion: method, the view controller that was presented has this property set to the view controller that presented it.

Upvotes: 13

Related Questions