How to get class name of parent ViewController in Swift?

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


First add extension in view controller

extension UIView {
    var parentViewController: UIViewController? {
        var parentResponder: UIResponder? = self
        while parentResponder != nil {
            parentResponder = parentResponder!.next
            if let viewController = parentResponder as? UIViewController {
                return viewController
            }
        }
        return nil
    }
}

Now Use it Like this

let vc = self.parentViewController

or

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

Here's one approach:

if let parentVC = parent as? SomeViewController {
    // parentVC is someViewController
} else if let parentVC = parent as? AnotherViewController {
    // parentVC is anotherViewController
}

This will conditionally assign and unwrap parent (the parent view controller) to its appropriate type. Within the condition blocks, parentVC will be the correct class.

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.


Simply use view.parentViewController and eventually its title property.