Reputation: 272234
Let's say I have a RestaurantViewController
. I'd like to embed 3 view controllers directly to fill this parent. (not covering nav bar of course).
In the navigation bar, there will be a button.
As I tap this button, the visibility of the 3 VCs will cycle. (no animations, just hiding/showing).
When I tap the button, I want the 3 childrens to respect events viewWillAppear
, viewWillDisappear
, etc... Does changing the hidden
property call these?
How can I do this?
My theory is to create 3 containers and add them to RestaurantViewController.view
, then set hidden for them as I tap the button. I'm not sure if this is the "right" way.
Upvotes: 0
Views: 97
Reputation: 131481
If you want each child to have it's own area of the screen then using 3 different containers with a different child in each will work fine.
No, viewWillAppear/viewWillDisappear will not be called each time the child's hidden flag switches from true to false. As Tj3n says, that will only be called if the child view controller's view is removed from the screen and then re-added.
If you have a single container view that you want to replace with a different child view controller each time you press a button then you want to use the parent/child view controller methods in UIViewController. See the section "Implementing a Container View Controller" in the Xcode docs on UIViewController.
You could add your starting child view controller to the container using an embed segue, and add the others using addChildViewController
.
There are also methods that let you transition from one child to another, like transitionFromViewController:toViewController:duration:options:animations:completion:
. That's a very powerful method that lets you swap child view controllers with a wide variety of transition effects. That's the method that you'd trigger when the user pressed the button to swap view controllers.
Upvotes: 3
Reputation: 382
You can add 3 UIViewControllers to the main view controller, but none of them will call viewWillAppear. Instead of playing with the property hidden you can add a tag value to each view do something like:
-(void)changeViews:(int) index {
if (lastDisplayedView == 1) {
// code you wanted in viewWillDisappear for view 1
} else if (lastDisplayedView == 2) {
// code you wanted in viewWillDisappear for view 2
} else if (lastDisplayedView == 3) {
// code you wanted in viewWillDisappear for view 3
}
UIView *viewToRemove = (UIView *)[self.view viewWithTag:lastDisplayedView];
[viewToRemove removeFromSuperview];
UIView *viewToShow = (UIView *)[self.view viewWithTag:index];
[self.view addSubview:viewToShow];
lastDisplayedView = index;
// code you need to do when view appears
}
Upvotes: 0