it-swarm.cn

检查子视图是否在视图中

我正在创建一个应用程序,我在IBAction上使用addSubview:向视图添加子视图。以同样的方式,当再次触摸带有IBAction的按钮时,应该在removeFromSuperview上添加的子视图上调用IBAction

PSEUDO代码

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

}
89
pmerino

您可能正在寻找UIView的-(BOOL)isDescendantOfView:(UIView *)view;中的 UIView类引用

返回值 YES如果接收者是视图的直接或远程子视图,或者视图是接收者本身;否则没有。

您将得到如下代码:

Objective-C的

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

斯威夫特3

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

试试这个:

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

Swift等价物看起来像这样:

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

检查子视图的超级视图......

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

你的if条件应该是这样的

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

}
1
Saran