How to add navigation interface after create a tab

2020-02-05 11:13发布

问题:

How do I add a navigation interface programmatically on Swift after I created a TabBarController on AppDelegate/didFinishLaunchingWithOptions. Here are my current codes:

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


    let tabBarController = UITabBarController()
    let purchaseViewController = PurchaseViewController(nibName: "PurchaseViewController", bundle: nil)
    let financeViewController = FinanceViewController(nibName: "FinanceViewController", bundle: nil)



    tabBarController.viewControllers = [purchaseViewController, financeViewController]

    self.window!.rootViewController = tabBarController
    self.window!.makeKeyAndVisible()

I'm looking at the documentation. It has the following guidelines

- (void)applicationDidFinishLaunching:(UIApplication *)application {
self.tabBarController = [[UITabBarController alloc] init];

MyViewController1* vc1 = [[MyViewController1 alloc] init];
MyViewController2* vc2 = [[MyViewController2 alloc] init];
MyViewController3* vc3 = [[MyViewController3 alloc] init];
MyNavRootViewController* vc4 = [[MyNavRootViewController alloc] init];
UINavigationController* navController = [[UINavigationController alloc]
                        initWithRootViewController:vc4];

NSArray* controllers = [NSArray arrayWithObjects:vc1, vc2, vc3, navController, nil];
tabBarController.viewControllers = controllers;

window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
window.rootViewController = tabBarController;
[window makeKeyAndVisible];
}

Problem, I can't figure out how to do this properly on Swift. I'm looking to setup and modify the NavigationBar in a separate method in the AppDelegate. Any thoughts?

回答1:

To create a navigation controller use:

var navigationController = UINavigationController(rootViewController: viewController));

Then just put it in the array:

tabBarController.viewControllers = [purchaseViewController, financeViewController, navigationController]

But, you can to add UIControls to navigation bar only after view controller did load. On applicationDidFinishLaunching: it's impossible, because the navigationBar is nil. Proper way is to add controls to navigationBar in the viewDidLoad()