Check if there is a view in the view

I am creating an application where I add subview to the view using addSubview: on IBAction . Similarly, when a button with this IBAction touches again, call removeFromSuperview on this preview added on this IBAction :

PSEUDO CODE

 -(IBAction)showPopup:(id)sender { System_monitorAppDelegate *delegate = (System_monitorAppDelegate *)[[UIApplication sharedApplication] delegate]; UIView *rootView = delegate.window.rootViewController.view; if([self popoverView] is not on rootView) { [rootView addSubview:[self popoverView]]; } else { [[self popoverView] removeFromSuperview]; } } 
+74
ios cocoa-touch uikit uiview
Sep 14 '11 at 18:38
source share
6 answers

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

The return value is YES if the receiver is a direct or remote subview view or if view is the receiver itself; otherwise NO.

As a result, you will get the code:

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() } } 
+218
Sep 14 '11 at 18:43
source share

Try the following:

 -(IBAction)showPopup:(id)sender { if (!myView.superview) [self.view addSubview:myView]; else [myView removeFromSuperview]; } 
+14
Sep 14 '11 at 18:41
source share
  UIView *subview = ...; if([self.view.subviews containsObject:subview]) { ... } 
+12
Sep 14 '11 at 18:43
source share

Check Supervisor Preview ...

 -(IBAction)showPopup:(id)sender { if([[self myView] superview] == self.view) { [[self myView] removeFromSuperview]; } else { [self.view addSubview:[self myView]]; } } 
+1
Sep 14 '11 at 18:41
source share

Your if condition should look like

 if (!([rootView subviews] containsObject:[self popoverView])) { [rootView addSubview:[self popoverView]]; } else { [[self popoverView] removeFromSuperview]; } 
+1
Sep 14 '11 at 19:18
source share

Swift's equivalent would look something like this:

 if(!myView.isDescendantOfView(self.view)) { self.view.addSubview(myView) } else { myView.removeFromSuperview() } 
+1
Jun 16 '15 at 10:02
source share



All Articles