我正在创建一个应用,我在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];
}
}
答案 0 :(得分:251)
您可能正在寻找UIView class reference中的UIView -(BOOL)isDescendantOfView:(UIView *)view;
。
返回值 如果接收器是直接的或远程的,则为是 视图的子视图或视图是接收者本身;否则没有。
您最终会获得如下代码:
- (IBAction)showPopup:(id)sender {
if(![self.myView isDescendantOfView:self.view]) {
[self.view addSubview:self.myView];
} else {
[self.myView removeFromSuperview];
}
}
@IBAction func showPopup(sender: AnyObject) {
if !self.myView.isDescendant(of: self.view) {
self.view.addSubview(self.myView)
} else {
self.myView.removeFromSuperview()
}
}
答案 1 :(得分:17)
试试这个:
-(IBAction)showPopup:(id)sender
{
if (!myView.superview)
[self.view addSubview:myView];
else
[myView removeFromSuperview];
}
答案 2 :(得分:11)
UIView *subview = ...;
if([self.view.subviews containsObject:subview]) {
...
}
答案 3 :(得分:2)
检查子视图的超级视图......
-(IBAction)showPopup:(id)sender {
if([[self myView] superview] == self.view) {
[[self myView] removeFromSuperview];
} else {
[self.view addSubview:[self myView]];
}
}
答案 4 :(得分:2)
Swift等价物看起来像这样:
if(!myView.isDescendantOfView(self.view)) {
self.view.addSubview(myView)
} else {
myView.removeFromSuperview()
}
答案 5 :(得分:1)
你的if条件应该是
if (!([rootView subviews] containsObject:[self popoverView])) {
[rootView addSubview:[self popoverView]];
} else {
[[self popoverView] removeFromSuperview];
}
答案 6 :(得分:0)
在这里,我们使用了两种不同的视图。父视图是我们要在其中搜索后代视图并检查是否添加到父视图的视图。
if parentView.subviews.contains(descendantView) {
// descendant view added to the parent view.
}else{
// descendant view not added to the parent view.
}