Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get class name of parent ViewController in Swift?

Tags:

Is there any way to get class name of parent VC in present (child) UIViewController? My 'child' VC (push) has two 'parent'UIViewControllers, so I would like to know which one is current parent?

like image 279
Marko Avatar asked Jan 28 '15 17:01

Marko


2 Answers

Here's one approach:

if let parentVC = self.parentViewController {
    if let parentVC = parentVC as? someViewController {
        // parentVC is someViewController
    } else if let parentVC = parentVC as? anotherViewController {
        // parentVC is anotherViewController
    }
}

First, assign and optionally unwrap self.parentViewController.

Second, use optional casting as?, and assign the view controller to parentVC if it works.

That said, this is a code smell - child view controllers should typically have no idea who their parent view controllers are. Whatever problem you're solving, you should probably solve it with tell, don't ask and delegation instead.

like image 194
Aaron Brager Avatar answered Sep 17 '22 15:09

Aaron Brager


UPDATED TO SWIFT 5

In your child view controller, you could try something like:

guard let parent = self.presentingViewController else{
    // ...some code
    return
}
//presented by parent view controller 1
if parent.isKind(of: Parent1.self){
    // do something
}else{
    //presented by parent view controller 2
}

I recommend you to place this logic in your viewWillAppear method because when viewDidLoad is called, there is no guarantee that the view controller hierarchy is loaded in the navigation tree and like a consequence of this, the presentingViewController property of your child view controller might be nil

like image 30
mauricioconde Avatar answered Sep 21 '22 15:09

mauricioconde