15

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.

chown
  • 51,908
  • 16
  • 134
  • 170

4 Answers4

44

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

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

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

thomas
  • 5,637
  • 2
  • 24
  • 35
17

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.
}
Shinnyx
  • 2,144
  • 2
  • 14
  • 21
4

I updated to Swift4, Thanks a lot to @Shinnyx and @thomas.

if viewB.superview != nil{     
    print("visible")
}
else{
   print("not visible")
}

if selfView.isDescendant(of: self.parentView) {
    print("visible")
}
else{
    print("not visible")
}

func isDescendant(of: UIView)

Returns a Boolean value indicating whether the receiver is a subview of a given view or identical to that view.

dengApro
  • 3,848
  • 2
  • 27
  • 41
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.

Hiren
  • 12,720
  • 7
  • 52
  • 72
Owen Hartnett
  • 5,925
  • 2
  • 19
  • 35
  • 2
    You can do this in the Xcode debugger with any view using `recursiveDescription` via `po [view recursiveDescription]` – Reid Ellis Oct 20 '15 at 18:38