ios 检查子视图是否在视图中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7421298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a subview is in a view
提问by pmerino
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
:
我在做一个应用程序,我一个子视图添加到使用视图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];
}
}
回答by
You are probably looking for UIView's -(BOOL)isDescendantOfView:(UIView *)view;
taken in UIView class reference.
您可能正在寻找-(BOOL)isDescendantOfView:(UIView *)view;
在UIView 类参考中采用的UIView。
Return ValueYES if the receiver is an immediate or distant subview of view or if view is the receiver itself; otherwise NO.
返回值YES 如果接收器是视图的直接或远处子视图,或者视图是接收器本身;否则否。
You will end up with a code like :
您最终会得到如下代码:
Objective-C
目标-C
- (IBAction)showPopup:(id)sender {
if(![self.myView isDescendantOfView:self.view]) {
[self.view addSubview:self.myView];
} else {
[self.myView removeFromSuperview];
}
}
Swift 3
斯威夫特 3
@IBAction func showPopup(sender: AnyObject) {
if !self.myView.isDescendant(of: self.view) {
self.view.addSubview(self.myView)
} else {
self.myView.removeFromSuperview()
}
}
回答by Mark Granoff
Try this:
尝试这个:
-(IBAction)showPopup:(id)sender
{
if (!myView.superview)
[self.view addSubview:myView];
else
[myView removeFromSuperview];
}
回答by Michael Frederick
UIView *subview = ...;
if([self.view.subviews containsObject:subview]) {
...
}
回答by JaySH
The Swift equivalent will look something like this:
Swift 等价物将如下所示:
if(!myView.isDescendantOfView(self.view)) {
self.view.addSubview(myView)
} else {
myView.removeFromSuperview()
}
回答by Jason Harwig
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]];
}
}
回答by Saran
Your if condition should go like
你的 if 条件应该像
if (!([rootView subviews] containsObject:[self popoverView])) {
[rootView addSubview:[self popoverView]];
} else {
[[self popoverView] removeFromSuperview];
}