Start second view controller of navigation stack f

2019-09-20 12:32发布

问题:

There is a default calendar app.

It starts with the next view controller and back button is already there like there some other view controller was started before this one:

When you press back button you get the next view controller:

How did they do it?

In my app I need the same logic (to start a view controller with the latest or default category but users can press back button to select a different category)

回答1:

If I were to do this, I would start by simply using pushViewController(animated:) to push the month view onto the navigation stack, with animated: false in the root view controller's viewWillAppear(animated:) method. The calendar would appear to the user already one level deep in the navigation stack.

So, the first controller is the year view, and then the month view is the second one pushed onto the stack, but it all happens before the user has seen any of the views. Simple, right?

Here are the docs for UINavigationController in case that helps.



回答2:

I think what you want is to push the view controllers once at start. An easy way to do it is to sub-class UINavigationController and assign it to the root navigation controller in your storyboard. Then simply do the work in your sub-class' viewWillAppear method, as this will be called exactly once at startup.

Of course, you can also accomplish the same result by using a flag to only load the next view controller once if you put the push code in the first view controller's viewWillAppear.

@interface MyNavigationController : UINavigationController

@end

@implementation MyNavigationController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    UIViewController *secondVC = [self.storyboard instantiateViewControllerWithIdentifier:@"secondVC"];
    [self pushViewController:secondVC animated:NO];
}

@end