Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a subview is in a view

People also ask

How do you check if a view contains a Subview?

Parent view is the view in which we are searching for descendant view and check wether added to parent view or not. if parentView. subviews. contains(descendantView) { // descendant view added to the parent view. }

How do I get Subviews in UIView Swift?

If you need a quick way to get hold of a view inside a complicated view hierarchy, you're looking for viewWithTag() – give it the tag to find and a view to search from, and this method will search all subviews, and all sub-subviews, and so on, until it finds a view with the matching tag number.


You are probably looking for UIView's -(BOOL)isDescendantOfView:(UIView *)view; taken in UIView class reference.

Return Value YES if the receiver is an immediate or distant subview of view or if view is the receiver itself; otherwise NO.

You will end up with a code like :

Objective-C

- (IBAction)showPopup:(id)sender {
    if(![self.myView isDescendantOfView:self.view]) { 
        [self.view addSubview:self.myView];
    } else {
        [self.myView removeFromSuperview];
    }
}

Swift 3

@IBAction func showPopup(sender: AnyObject) {
    if !self.myView.isDescendant(of: self.view) {
        self.view.addSubview(self.myView)
    } else {
        self.myView.removeFromSuperview()
    }
}

Try this:

-(IBAction)showPopup:(id)sender
{
    if (!myView.superview)
        [self.view addSubview:myView];
    else
        [myView removeFromSuperview];
}

    UIView *subview = ...;
    if([self.view.subviews containsObject:subview]) {
        ...
    }

The Swift equivalent will look something like this:

if(!myView.isDescendantOfView(self.view)) {
    self.view.addSubview(myView)
} else {
    myView.removeFromSuperview()
}

Check the superview of the subview...

-(IBAction)showPopup:(id)sender {
    if([[self myView] superview] == self.view) { 
        [[self myView] removeFromSuperview];           
    } else {
        [self.view addSubview:[self myView]];         
    }
}

Your if condition should go like

if (!([rootView subviews] containsObject:[self popoverView])) { 
    [rootView addSubview:[self popoverView]];
} else {
    [[self popoverView] removeFromSuperview];

}