how to get navigation controller from NSObject cla

2019-09-13 23:32发布

问题:

I am working in a static library project and I want to push a view controller in navigation controller of iOS project How can I do it ? I am doing it as follows:

  UIStoryboard * storyboard = [[[UIApplication sharedApplication] keyWindow] rootViewController].storyboard;
UIViewController* pushtoVC = [storyboard instantiateViewControllerWithIdentifier:@"home"];
UINavigationController *navController = [[[[UIApplication sharedApplication] keyWindow]rootViewController] navigationController];
[navController pushViewController:pushtoVC animated:YES];

I have also tried the following code but its is not pushing view controller.

  UIStoryboard * storyboard = [[[UIApplication sharedApplication] keyWindow] rootViewController].storyboard;
UIViewController* pushtoVC = [storyboard instantiateViewControllerWithIdentifier:@"home"];
UINavigationController *navController = [[[[UIApplication sharedApplication] keyWindow]rootViewController] navigationController];
[navController pushViewController:pushtoVC animated:YES];

But if I am using present view controller modally it is working but navigation controller hides only View controller was loaded. the code which is working to present modally without navigation controller is as follows.

 UIStoryboard * storyboard = [[[UIApplication sharedApplication] keyWindow] rootViewController].storyboard;
            if ([[storyboard valueForKey:@"identifierToNibNameMap"] objectForKey:@"home"]) {
                // the view controller exists, instantiate it here
                UIViewController* myVC = [storyboard instantiateViewControllerWithIdentifier:@"home"];
                myVC.modalPresentationStyle = UIModalPresentationFullScreen;
                [[[[UIApplication sharedApplication]keyWindow] rootViewController] presentViewController:myVC animated:YES completion:nil];

the above code is presenting view controller modally but navigation controller removed from view controller but I want to navigate to home view controller with navigation controller.

回答1:

It isn't entirely clear exactly what you're trying to do, so arguably you should be passing a controller to use for presentation or passing a controller back to something else who knows how to present it...

Anyway, I guess your root VC is a navigation controller so you should be using that directly instead of asking it for its navigation controller (which is nil).

UINavigationController *navController = (UINavigationController *)[[[UIApplication sharedApplication] keyWindow] rootViewController];
[navController pushViewController:pushtoVC animated:YES];


回答2:

same answer in Swift 4

var navController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController
navController?.pushViewController(pushtoVC, animated: true)