Atharva
Atharva

Reputation: 6969

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

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.

Upvotes: 7

Views: 3293

Answers (3)

Stopshe
Stopshe

Reputation: 73

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

Upvotes: 5

rishi
rishi

Reputation: 11839

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];
    

Upvotes: 0

Mayank Jain
Mayank Jain

Reputation: 5754

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;

Upvotes: 5

Related Questions