I have a bunch of subViews in my ViewController.
In the last layer I have a UIView, and from this view I want to call superview and go up until I find the UIView that belongs to my ViewController.
Is it possible to find out whether a UIView belongs to a ViewController or not?
UIView *someView = self.superView;
while (true)
{
if (someView BELONGS TO VIEWCONTROLLER)
{
// Now we know this view belongs to a VIewController
break;
}
someView = someView.superView;
}
If you want to find out if a certain view is in the hierarchy managed by a view controller and you have a pointer to the view controller:
BOOL belongsToController = [aView isDescendantOfView:viewController.view];
Alternatively, if you want to find out if a certain view is the root of the hierarchy managed by the view controller but you don't have a pointer to the view controller, you can traverse the responder chain. According to the UIResponder
's nextResponder documentation:
UIView
implements this method by returning theUIViewController
object that manages it (if it has one) or its superview (if it doesn’t)
Therefore, if the next responder of a certain view is a UIViewController
, that view must be the view associated with the view controller.
if ([[aView nextResponder] isKindOfClass:[UIViewController class]]) {
// aView is the root of the view hierarchy managed by the view controller
}
Vlad's and albertamg's approaches are correct as well. However you can also traverse the responder chain
for (UIView* next = [self superview]; next; next = next.superview) {
UIResponder* nextResponder = [next nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]]) {
UIViewController *theControllerThatYouWANT = (UIViewController*)nextResponder;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With