通过initWithRootViewController以外的方法设置UINavigationController的rootViewController

时间:2013-04-25 12:40:04

标签: ios uinavigationcontroller uitoolbar iphone-5

如何通过rootViewController以外的方法设置UINavigationController的{​​{1}}?

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

5 个答案:

答案 0 :(得分:129)

您可以致电setViewControllers来解决此问题。

像这样:

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

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

答案 1 :(得分:24)

使用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)

我们可以编写类似于this.

的泛化方法

答案 2 :(得分:11)

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

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

答案 3 :(得分: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)

答案 4 :(得分:-1)

  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()
    })