What is called when removing a view from its superview?
Imagine I have a view controller called blueView
and another called greenView
. I then add greenView.view
as a subview of blueView.view
. Now suppose that after some user interaction, I'd like to remove greenView.view
from blueView.view
using:
[self.view removeFromSuperview]
What is actually happening here? Is blueView.view
ever redrawn? I thought the viewDidLoad
method might be called, however afte开发者_如何学编程r putting an NSLog
messge in viewDidLoad
, it was never called after removing the subview. Any clarification as to what is actually happening when you remove a subview from its superview would be much appreciated.
First, a view controller is meant to manage an entire view hierarchy at once; you shouldn't have two view controllers (other than container controllers like UINavigationController) active at the same time. See this SO question and my answer to get a better understanding on this important point. So, the particular situation you describe shouldn't come up. (Aside: people often confuse views and view controllers, so it's not helpful to give your view controllers names ending in "-view", like "blueView." Call it "blueViewController" to help avoid confusion.)
Second, as @InsertWittyName points out, -viewDidLoad
is a UIViewController method, not a UIView method. Taking that a step further, neither view controllers nor -viewDidLoad
has any role in adding or removing subviews from a view. -viewDidLoad
is called when the view controller's view is first created. It's basically just a way of deferring the view-related part of view controller initialization until after the view hierarchy has been created, so there's no reason that it'd be called again just because a subview was removed from the hierarchy.
Finally, exactly how a view removes itself from its superview is really an implementation detail -- it might call a private UIView method on the superview, or it might modify the superview's list of subviews directly, or something else. I don't see anything in the documentation that explicitly says that the superview will redraw itself after a subview has been removed, but in my experience the superview does indeed redraw itself. You can check this by putting a breakpoint on the -drawRect
method of the superview.
精彩评论