开发者

Remove current view from superview

开发者 https://www.devze.com 2023-03-10 06:42 出处:网络
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 ViewAViewControlle

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 f开发者_StackOverflow中文版irst 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 (i.e. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消