How to show ViewController from a non-ViewController helper class?

馋奶兔 提交于 2021-02-19 01:43:13

问题


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 -

  1. 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

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!