检查子视图是否在视图中

我正在制作一个应用程序,其中我添加一个子视图到一个视图使用 addSubview:上的 IBAction。同样,当再次触摸到 IBAction的按钮时,应该调用添加在 IBAction上的子视图上的 removeFromSuperview:

伪代码

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


}
89843 次浏览

Try this:

-(IBAction)showPopup:(id)sender
{
if (!myView.superview)
[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]];
}
}

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()
}
}
    UIView *subview = ...;
if([self.view.subviews containsObject:subview]) {
...
}

Your if condition should go like

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


}

The Swift equivalent will look something like this:

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

Here we used two different views. 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.
}else{
// descendant view not added to the parent view.
}