How to push multiple view controllers onto navigat

2019-08-14 04:23发布

问题:

Newbie here programming my first app (having made several tutorial apps). I am using a view controller called 'RootViewController' as a navigation controller. I have successfully pushed another view controller on top of this called 'ClientListViewController' using the command:

[self.navigationController pushViewController:clientListViewController animated:YES];

I am now in the ClientListViewController and trying to push another view controller onto the stack called 'AddClientViewController'. I would like to make this a modal view controller in the form of a UIModalPresentationFormSheet. I am trying to use a variation of the command above to push the new view controller but i don't know how to replace the 'self'. I have tried:

[RootViewController.navigationController pushViewController:AddClientViewController animated:YES];

and...

[[RootViewController navigationController] pushViewController:AddClientViewController animated:YES];

as well as each of these combinations using small 'R's for the word Root. Still no luck.

For clarity, I have used the following code at the top of my implementation file.

#import "AddClientViewController.h"

Am I approaching this in the right way, or should I be using a brand new navigation controller to add it to?

Any pointers greatly received.

Many thanks

回答1:

Every UIViewController has a property named navigationController. This property refers to the nearest enclosing UINavigationController, if there is one. So you can just say self.navigationController in your ClientListViewController.

In iOS, we normally capitalize class names. So it sounds like AddClientViewController is a class name. You need to have an instance of that class to push it on the navigation controller's stack. Something like this:

AddClientViewController *addClientVC = [[AddClientViewController alloc] init];
[self.navigationController pushViewController:addClientViewController animated:YES];

You might need to use a different init method or set some properties of addClientVC before pushing it; that depends on your implementation of AddClientViewController.

If you want to present it modally, you don't push it on the navigation controller's stack. Instead you do it this way:

AddClientViewController *addClientVC = [[AddClientViewController alloc] init];
addClientVC.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:addClientVC animated:YES completion:nil];