Is there a built-in way to get from a UIView
to its UIViewController
? I know you can get from UIViewController
to its UIView
I stumbled upon a situation where I have a small component I want to reuse, and added some code in a reusable view itself(it's really not much more than a button that opens a PopoverController
).
While this works fine in the iPad (the UIPopoverController
presents itself, therefor needs no reference to a UIViewController
), getting the same code to work means suddenly referencing your presentViewController
from your UIViewController
. Kinda inconsistent right?
Like mentioned before, it's not the best approach to have logic in your UIView. But it felt really useless to wrap the few lines of code needed in a separate controller.
Either way, here's a swift solution, which adds a new property to any UIView:
extension UIView {
var viewController: UIViewController? {
var responder: UIResponder? = self
while responder != nil {
if let responder = responder as? UIViewController {
return responder
}
responder = responder?.nextResponder()
}
return nil
}
}