如何以编程方式创建标签栏控制器后添加导航界面(Swift)
Posted
技术标签:
【中文标题】如何以编程方式创建标签栏控制器后添加导航界面(Swift)【英文标题】:How to add navigation interface after create a tab bar controller programmatically (Swift) 【发布时间】:2014-12-21 16:30:43 【问题描述】:在AppDelegate/didFinishLaunchingWithOptions
上创建TabBarController
后,如何以编程方式在Swift 上添加导航 界面。这是我当前的代码:
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()
我正在查看文档。它有以下准则
- (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];
问题,我不知道如何在 Swift 上正确执行此操作。我希望在AppDelegate
中以单独的方法设置和修改NavigationBar
。有什么想法吗?
【问题讨论】:
【参考方案1】:要创建导航控制器,请使用:
var navigationController = UINavigationController(rootViewController: viewController));
然后直接放入数组中:
tabBarController.viewControllers = [purchaseViewController, financeViewController, navigationController]
但是,您只能在视图控制器加载后才能将 UIControls 添加到导航栏。在applicationDidFinishLaunching:
上是不可能的,因为navigationBar 是零。正确的方法是在viewDidLoad()中给navigationBar添加控件
【讨论】:
感谢您的评论。我不确定我是否遵循您的建议。回复:var navigationController = UINavigationController(rootViewController: viewController));如上所示,在我的 App Delegate 设置中,我创建了一个 TabBarControllers 和 2 个 viewControllers。鉴于我尚未为该代码创建 viewController 标识符以使其正常工作,我该如何遵循您的建议? 如果您需要每个视图控制器的导航栏,请创建两个不同的导航控制器,并将您的视图控制器作为根视图控制器。示例:var navigationController1 = UINavigationController(rootViewController: purchaseViewController); tabBarController.viewControllers = [navigationController1, navigationController2]
以上是关于如何以编程方式创建标签栏控制器后添加导航界面(Swift)的主要内容,如果未能解决你的问题,请参考以下文章