Friday, July 31, 2015

iOS View Controller Containment

A best example of Container view controllers are Tab View Controllers. In essence, this is about containing other controllers inside one controller. Before iOS 5.0 view controller containers were existing only in the framework classes. 

When designing a container, we are establishing a parent child relation ship between container and its child controllers. A container can add the content views of other view controllers in its own view hierarchy Whenever child view is displayed in containers view, the Controller also establishes a connection to the child view controller and ensure that all appropriate view controller events are sent to the child. 

Below is the code to add a child view controller to a Customer Container view controller 

-(void) addChildViewController:(UIViewController*) content 
{
[self addChildViewController:content];
content.view.frame = self.view.frame;
[self.view addSubView:content.view];
[content didMoveToParentViewController:self];
}

When a child view Controller is added to a controller, its willMoveToParentViewController will be called automatically. 

To remove a child controller from a Container view controller, below can be used

-(void) removeChildViewController:(UIViewController*) content
{
[content willMoveToParentViewController:nil];
[self.view removeFromSuperView:content.view];
[content removeFromParentViewController:nil];
}

For a container with essentially static contents, adding and removing view controllers is simple like above. Sometimes we would want to animate a view into the scene while simultaneously removing another child. 

-(void) tranitionToNewViewController:(UIViewController*)newVC oldVC:(UIViewController*)oldVC
{
[oldVC willMoveToParentViewController:nil];
[self addChildViewController:newVC];
self transitionFromViewController:oldVC toNewViewController:newVC
duration:0.25 options:0
animations:^{
newVC.view.frame = oldVC.view.frame;
oldVC.view.frame = endFrame;
}
completion:^{
[oldVC removeFromParentViewController];
[newVC didMoveToParentViewController:self];
}
}


References:


No comments:

Post a Comment