开发者

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

开发者 https://www.devze.com 2023-04-13 04:20 出处:网络
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.

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.


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


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.
}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号