检查子视图是否在视图中 [英] Check if a subview is in a view

查看:123
本文介绍了检查子视图是否在视图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个应用程序,在其中使用 addSubview: IBAction 上向视图添加子视图。以同样的方式,当再次触摸具有 IBAction 的按钮时,应该在该子视图上添加 removeFromSuperview code> IBAction :

I'm making an app where I add a subview to a view using addSubview: on an IBAction. In the same way, when the button with that IBAction is touched again should call removeFromSuperview on that subview added on that 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];
    }

}


推荐答案

您可能正在寻找UIView的 - (BOOL)isDescendantOfView:(UIView *)view; IVIView类别参考

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 :

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



Swift



Swift

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

这篇关于检查子视图是否在视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆