I have a view controller that when I press a button a child view controller appear. This works perfectly but I want to change this child view controller for other one if I p
If using storyboards, you can create your own child replace segue, e.g.:
ReplaceSegue.h
@interface ReplaceSegue : UIStoryboardSegue
@end
ReplaceSegue.m
@implementation ReplaceSegue
- (void)perform
{
UIViewController *source = self.sourceViewController;
UIViewController *destination = self.destinationViewController;
UIViewController *container = source.parentViewController;
[container addChildViewController:destination];
destination.view.frame = source.view.frame;
[source willMoveToParentViewController:nil];
[container transitionFromViewController:source
toViewController:destination
duration:0.5
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
}
completion:^(BOOL finished) {
[source removeFromParentViewController];
[destination didMoveToParentViewController:container];
}];
}
@end
You can then open your storyboard, put a container view on your container view controller and on the child controller, put a custom segue from the first child scene to the second child scene. You'll want to specify the ReplaceSegue
class for the custom segue between the two child scenes:
Note that if you've properly used autolayout or autosizing on the second child view, everything will work fine (especially with the manual setting of the frame of the destination controller's view in the ReplaceSegue
). But in Interface Builder, the layout of that second child scene doesn't look quite right and can make the proper design of the scene a little awkward, because (as of Xcode 4.5, at least) the "Simulated Metrics" for the second child scene doesn't do a good job inferring the the proper size. So you should probably change that second child scene's simulated metrics' size from "Inferred" to "Freeform" and then manually adjust the size of the second child scene:
It's not very elegant Xcode experience, but it works. And if you're properly using autolayout or autosizing masks, minor variations are handled very gracefully.