How to check if a UIView is a subview of a parent view

| | August 4, 2015

I have an app which I add a subview to (and remove the same subview based on user interactions). I am looking for a way to check whether the subview is present or not at any given time.

For example:

In the current view (UIView *viewA) I add a subview (UIView *viewB). I then want a way of checking whether viewB is being displayed at any given time.

Sorry if this isn’t very clear, it’s quite hard to describe.

3 Responses to “How to check if a UIView is a subview of a parent view”

  1. I went through the same issue and consulted Apple Documentation and came up with this elegant solution:

    if([self.childView isDescendantOfView:self.parentView])
        // The childView is contained in the parentView.
  2. Here’s a method I put in the appDelegate so that I can display the entire subview hierarchy from any point.

    // useful debugging method - send it a view and it will log all subviews
    // can be called from the debugger
    - (void) viewAllSubviews:(UIView *) topView Indent:(NSString *) indent  {
        for (UIView * theView in [topView subviews]){
            NSLog(@"%@%@", indent, theView);
            if ([theView subviews] != nil)
                [self viewAllSubviews:theView Indent: [NSString stringWithFormat:@"%@ ",indent]];

    call it with a string with one character and it will indent for you. (i.e. [appDelegate viewAllSubviews:self.view Indent:@" "];)

    I find it useful to clear the debug pane first, then call this from the debugger, and copy it into a text editor like BBEdit that will show the indents.

    You can call it using the mainWindow’s view and see everything on your screen.

  3. an UIView stores its superview and is accessible with the superview-property just try

    if([viewB superview]!=nil)
        NSLog(@"not visible");

    But the better approach is to use the hidden-property of UIView

Leave a Reply