Ich erstelle eine App, in der ich einer Ansicht eine Unteransicht mit addSubview:
Auf einem IBAction
hinzufüge. Auf die gleiche Weise sollte, wenn die Schaltfläche mit diesem IBAction
erneut berührt wird, removeFromSuperview
in der Unteransicht aufgerufen werden, die zu diesem IBAction
hinzugefügt wurde:
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];
}
}
Sie suchen wahrscheinlich nach -(BOOL)isDescendantOfView:(UIView *)view;
von UIView, aufgenommen in IView-Klassenreferenz .
Rückgabewert JA, wenn der Empfänger eine unmittelbare oder entfernte Unteransicht der Ansicht ist oder wenn die Ansicht der Empfänger selbst ist; sonst NEIN.
Sie erhalten einen Code wie:
- (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()
}
}
Versuche dies:
-(IBAction)showPopup:(id)sender
{
if (!myView.superview)
[self.view addSubview:myView];
else
[myView removeFromSuperview];
}
UIView *subview = ...;
if([self.view.subviews containsObject:subview]) {
...
}
Das Swift Äquivalent sieht ungefähr so aus:
if(!myView.isDescendantOfView(self.view)) {
self.view.addSubview(myView)
} else {
myView.removeFromSuperview()
}
Überprüfen Sie die Übersicht der Unteransicht ...
-(IBAction)showPopup:(id)sender {
if([[self myView] superview] == self.view) {
[[self myView] removeFromSuperview];
} else {
[self.view addSubview:[self myView]];
}
}
Ihre If-Bedingung sollte wie folgt lauten
if (!([rootView subviews] containsObject:[self popoverView])) {
[rootView addSubview:[self popoverView]];
} else {
[[self popoverView] removeFromSuperview];
}