86

如何通过 以外的方法设置rootViewControllerof ?UINavigationControllerinitWithRootViewController

我想使用initWithNavigationBarClass:toolbarClass:为我的 NavigationController 提供自定义工具栏,所以我认为我不能使用initWithRootViewController.

4

5 回答 5

158

你可以通过调用来解决这个问题setViewControllers

像这样:

UINavigationController *navigationController = [[UINavigationController alloc] initWithNavigationBarClass:[MyNavigationBar class] toolbarClass:[UIToolbar class]];

[navigationController setViewControllers:@[yourRootViewController] animated:NO];

斯威夫特版本:

let navigationController = UINavigationController(navigationBarClass: MyNavigationBar.self, toolbarClass: UIToolbar.self)

navigationController.setViewControllers([yourRootViewController], animated: false)
于 2013-04-25T12:45:40.673 回答
30

使用 Swift 进行知识共享:

从 app delegate.swift 以外的类更改根视图控制器

let appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var homeViewController = mainStoryboard.instantiateViewControllerWithIdentifier("HomeViewController") as! HomeViewController
let nav = UINavigationController(rootViewController: homeViewController)
appdelegate.window!.rootViewController = nav

希望这对某人有帮助。

使用动画更改 rootviewcontroller 可以通过以下方式实现:

UIView.transitionWithView(self.window!, duration: 0.5, options: UIViewAnimationOptions.TransitionFlipFromLeft, animations: {
    self.window?.rootViewController = anyViewController
}, completion: nil)

我们也可以写一个通用的方法,类似于这个。

于 2015-04-25T06:40:13.757 回答
15

这个对我有用,希望对你有帮助

let rootVC:LoginViewController = self.storyboard?.instantiateViewControllerWithIdentifier("LoginViewController") as! LoginViewController
let nvc:UINavigationController = self.storyboard?.instantiateViewControllerWithIdentifier("RootNavigationController") as! UINavigationController
nvc.viewControllers = [rootVC]
UIApplication.sharedApplication().keyWindow?.rootViewController = nvc
于 2016-08-15T12:27:59.120 回答
2

在 swift 3.0 xcode8.1

在主界面中的常规设置中删除: Main <-this 在主界面之后:

class AppDelegate...

 var window: UIWindow?

    fun application...

      window = UIWindow(frame: UIScreen.main.bounds)
      window?.makeKeyAndVisible()
      window?.rootViewController = UINavigationController(rootViewController: NewYourController)
于 2016-11-01T20:50:52.073 回答
-3
  let storyboard = UIStoryboard(name: "Main", bundle: nil)         
  let yourNewRootView = storyboard.instantiateViewControllerWithIdentifier("yourNewRootView") as? yourNewRootView


   self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

    UIView.transitionWithView(self.window!, duration: 0.1, options: [UIViewAnimationOptions.TransitionFlipFromRight,UIViewAnimationOptions.TransitionFlipFromLeft], animations: 
    {
        // animation

        }, completion: { (finished: Bool) -> () in

            self.window?.rootViewController = nil
            self.window?.rootViewController = yourNewRootView
            self.window?.makeKeyAndVisible()
    })
于 2016-01-12T13:55:42.467 回答