How to check if a UIView is a subview of a parent view
Asked Answered
A

4

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.

Aporia answered 16/10, 2011 at 19:54 Comment(0)
C
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

Committee answered 16/10, 2011 at 19:59 Comment(0)
W
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.
}
Wenonawenonah answered 4/8, 2015 at 20:3 Comment(0)
B
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.

Bombazine answered 22/3, 2018 at 7:37 Comment(0)
B
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.

Bine answered 16/10, 2011 at 20:13 Comment(1)
You can do this in the Xcode debugger with any view using recursiveDescription via po [view recursiveDescription]Acis

© 2022 - 2024 — McMap. All rights reserved.