Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping a UIViewController in a UINavigationController

I'd like my view controller to have its own navigation bar. I find this is easier than showing/hiding the existing navigation bar. The following code is working. Is this an anti-pattern or is it relatively common practice?

MyViewController *viewController = [[MyViewController alloc] init] 
                                    autorelease];

UINavigationController *wrapper = [[[UINavigationController alloc] 
                                   initWithRootViewController:viewController] 
                                    autorelease];

[self.navigationController presentViewController:wrapper 
                                        animated:YES 
                                      completion:nil];
like image 457
SundayMonday Avatar asked Oct 02 '12 20:10

SundayMonday


People also ask

What is UIViewController in Swift?

The UIViewController class defines the shared behavior that's common to all view controllers. You rarely create instances of the UIViewController class directly. Instead, you subclass UIViewController and add the methods and properties needed to manage the view controller's view hierarchy.

Can any UIViewController push another?

Yes, you can push or present another view controller without any action. You just need to call the push or present code where you want to trigger it.

How do I push a presented Viewcontroller?

VC3 -> present VC2 -> VC1 VC2 needs to be in a UINavigationController then after you present it you can push VC3. The back button will work as expected on VC3, for VC2 you should call dismiss when the back button is pressed. Try implementing some of that in code and then update your question.

What is UIViewController life cycle?

The LifecycleThe view controller lifecycle can be divided into two big phases: the view loading and the view lifecycle. The view controller creates its view the first time the view is accessed, loading it with all the data it requires. This process is the view loading.


2 Answers

To present a modal view controller with a nav bar and its own navigation stack, the code you posted is exactly right. The only thing you should be careful of is pushing a second UINavigationController onto an existing nav controller's stack -- that will cause you problems.

like image 54
Joe Hankin Avatar answered Oct 11 '22 05:10

Joe Hankin


In Swift:

let mainViewController = MainViewController()
let navigationController = UINavigationController(rootViewController: mainViewController)
present(navigationController, animated: true, completion: nil)
like image 30
Umit Kaya Avatar answered Oct 11 '22 06:10

Umit Kaya