检查子视图是否在视图中

我正在做一个应用程序,我添加一个子视图到一个视图使用addSubview:在一个IBAction 。 以同样的方式,当再次触摸具有该IBAction的button时,应该在该IBAction上添加的该子视图上调用removeFromSuperview

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]; } } 

你可能正在寻找UIView的-(BOOL)isDescendantOfView:(UIView *)view; 采取UIView类参考 。

返回值如果接收器是立即或远距离的子视angular或者视angular是接收器本身,则返回 YES; 否则NO。

你会得到一个像这样的代码:

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() } } 

尝试这个:

 -(IBAction)showPopup:(id)sender { if (!myView.superview) [self.view addSubview:myView]; else [myView removeFromSuperview]; } 
  UIView *subview = ...; if([self.view.subviews containsObject:subview]) { ... } 

检查子视图的超级视图…

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

你的条件应该像

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

Swift相当于这样的:

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