检查子视图是否在视图中

pme*_*ino 93 cocoa-touch uikit uiview ios

我在做一个应用程序,我一个子视图添加到使用视图addSubview:IBAction.以同样的方式,当IBAction再次触摸带有该按钮的按钮时,应该调用removeFromSuperview添加在该子视图上的子视图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];
    }

}
Run Code Online (Sandbox Code Playgroud)

小智 263

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

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

您将得到如下代码:

Objective-C的

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

斯威夫特3

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

  • 不起作用,仅在其上添加视图。我将编辑代码以显示实际情况 (2认同)

Mar*_*off 17

试试这个:

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


Mic*_*ick 11

    UIView *subview = ...;
    if([self.view.subviews containsObject:subview]) {
        ...
    }
Run Code Online (Sandbox Code Playgroud)

  • @pmerino恭喜你那么懒,你也复制了"zad0xsis 1分钟前编辑":-) (11认同)