Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - Does UIView belong to a UIViewController?

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;
}
like image 764
aryaxt Avatar asked Aug 12 '11 05:08

aryaxt


2 Answers

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 the UIViewController 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
}
like image 107
albertamg Avatar answered Oct 19 '22 20:10

albertamg


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;
    }
  }
like image 45
Abhinit Avatar answered Oct 19 '22 21:10

Abhinit