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
.