Access view controller from any view Swift 5

In order to access the view controller from any view or subview, we are going use UIResponder Extension so you only need to write just one line of code.
extension UIResponder {
  
  func getOwningViewController() -> UIViewController? {
    var nextResponser = self
    while let next = nextResponser.next {
      nextResponser = next
      if let viewController = nextResponser as? UIViewController {
        return viewController
      }
    }
    return nil
  }
}

In the above function we are exploring the next responder until we find the UIViewController. You can call the above function from any view like below and get the responsible UIViewController.
if let viewController = self.myView.getOwningViewController() {
  print(viewController)
}
You can even access the above function inside your UITableViewCell class to get responsible UIViewController.

Leave a Reply

Your email address will not be published. Required fields are marked *