问题
Usually we call self.presentViewController(...) from some UIViewController object, but how to show a new view controller from a class type (static) function in a helper class which is not a UIViewController.
回答1:
You can show your viewController from helper class as root view controller of navigationcontroller
UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
UINavigationController *controller = (UINavigationController*)[storyBoard
instantiateViewControllerWithIdentifier: @"RootNavigationController"]; //set storyboard ID to your root navigationController.
YourViewController *vc = [storyBoard instantiateViewControllerWithIdentifier:@"YourViewController"]; // //set storyboard ID to viewController.
[controller setViewControllers:[NSArray arrayWithObject:vc] animated:YES];
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.window.rootViewController=controller;
回答2:
Mayank Jain's answer in swift 4:
var storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
var controller = storyBoard.instantiateViewController(withIdentifier: "RootNavigationController") as? UINavigationController
//set storyboard ID to your root navigationController.
var vc = storyBoard.instantiateViewController(withIdentifier: "YourViewController") as? YourViewController
// //set storyboard ID to viewController.
controller?.setViewControllers([vc], animated: true)
var appDelegate = UIApplication.shared.delegate as? AppDelegate
appDelegate?.window?.rootViewController = controller
回答3:
It is directly not possible, you always need a view controller/navigation controller instance. but there are some possible work around.
It depends on requirement, how you want to use it. some of suggestions -
application delegate's navigation controller is accessible everywhere, you can use it.
YourAppDelegate *delegate = (YourAppDelegate *) [UIApplication sharedApplication].delegate;
now you can use -
delegate.window.rootViewController.navigationController
In helper method instance itself pass instance of navigation controller from where you are calling it. Some thing like -
+(void)myHelperMethodWithNavigationController:(UINavigationController*)navController { ------- [navController pushViewController:yourNewCreatedController animated:YES]; }
while calling this from some view controller -
[MyHelperClass myHelperMethodWithNavigationController:self.navigationController];
来源:https://stackoverflow.com/questions/28314228/how-to-show-viewcontroller-from-a-non-viewcontroller-helper-class