如何从非ViewController帮助器类中显示ViewController?

时间:2015-02-04 05:38:40

标签: ios objective-c swift

通常我们从一些UIViewController对象调用self.presentViewController(...),但是如何在一个不是UIViewController的辅助类中从类类型(静态)函数中显示一个新的视图控制器。

3 个答案:

答案 0 :(得分:4)

您可以将helper类中的viewController显示为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;

答案 1 :(得分:3)

Mayank Jain在快速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

答案 2 :(得分:0)

直接不可能,您总是需要一个视图控制器/导航控制器实例。但是有一些可能的工作。

这取决于要求,您希望如何使用它。一些建议 -

  1. 应用程序委托的导航控制器随处可访问,您可以使用它。

      YourAppDelegate *delegate = (YourAppDelegate *) [UIApplication sharedApplication].delegate;
    

    现在您可以使用 - delegate.window.rootViewController.navigationController

  2. 在辅助方法实例中,从您调用它的位置传递导航控制器的实例。 有点像 -

    +(void)myHelperMethodWithNavigationController:(UINavigationController*)navController {
      -------
      [navController pushViewController:yourNewCreatedController animated:YES];
     }
    
    从某个视图控制器调用它时

    -

    [MyHelperClass myHelperMethodWithNavigationController:self.navigationController];