简体   繁体   中英

Remove current view from superview

Let's say I have a viewcontroller "ViewBViewController". In that viewcontroller I create an instance of the "ViewAViewController" and use the addSubView: method to display this ViewAViewController. It then processes a bunch of information, and is now done. I want it to automatically get removed as a subview when it's done.

I was looking at the removeFromSuperview method, but can't seem to call that from within the viewcontroller whose view I'm trying to remove (my first instinct was [self.view removeFromSuperview], but that gets rid of the entire view, not just the subview I'm after).

The only way I can think of is setting up a delegate protocol, and have View B take care of the unloading of View A on behalf of View A as its delegate. However this approach seems a bit overkill. Am I missing an easier solution?

Thanks in advance!

UIViewController does not respond to removeFromSuperview , because a UIViewController is not a UIView but a UIViewController . No surprises there. You can call removeSuperview on any view, such as the view associated to a view controller (here self ):

[self.view removeFromSuperview];

or if you just want to remove one subview:

[mySubview removeFromSuperview];

or if your subview is a member of self (ie declared in the interface say):

[self.mySubview removeFromSuperview];

Have you tried: setHidden: YES ?

There are two basically correct solutions here:

  • Use a navigation controller. You can hide the navigation bar if you don't want it to be part of your interface. Then you can dispose of the top view controller and its view from either view controller by calling

    // argument can be YES or NO, as you like [self.navigationController popViewControllerAnimated:YES];
  • Use a delegate call that tells the parent view controller to do something like

    -(void)removeViewA { // remove the view from the view hierarchy [self.viewAController.view removeFromSuperview]; // dispose of the view controller so it doesn't leak. self.viewAController = nil; }

It's important to make sure that you don't leak the child view controller and its view.

Either of these approaches works, but using a navigation controller seems more idiomatic to me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM