iosuiviewuiviewcontrollersuperview

How do I find the most parent SuperView?


I'm trying to add a new subView to a page, such that everything but itself is greyed out. However, I'm calling it from within a subview of the screen. To get it out, I have to do the following :

[self.view.superview.superview.superview.superview addSubview:self.cardDialog.view];

As you can surmise, this is extremely bad code. How can I find the proper parent level and set it correctly?


Solution

  • If the view is part of the view hierarchy, use the window property.

    UIView* topView = self.view.window;
    

    Or if your view is not on screen yet, you can get the window indirectly through your app delegate

    UIView* topView = [UIApplication sharedApplication].delegate.window;
    

    Else, if your target is not the window, you can walk up the view hierarchy until you find the view you want:

    UIView* topView = self.view;
    
    while(topView.superview != nil){
        topview = topView.superview;
    
        if( /*topview is the one you were looking for*/ ){
            break;
        }
    }