UINavigationController和TabBarController以编程方式(没有故事板)

Big*_*son 2 xcode ios swift swift3 xcode8

目前,我的AppDelegate文件包含此代码,以将CustomTabBarController建立为rootViewController:

window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = CustomTabBarController()
Run Code Online (Sandbox Code Playgroud)

我希望我的应用程序始终在底部有CustomTabBarController,但我希望每个选项卡都有一个导航控制器.这是我用来设置tabBarController的代码:

class CustomTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
let vc1 = FirstViewController()
let vc2 = SecondViewController()
let vc3 = ThirdViewController()
viewControllers = [vc1, vc2, vc3]
}
Run Code Online (Sandbox Code Playgroud)

这是我用来设置FirstViewController的代码:

class ProfileViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 2
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: VCCellId, for: indexPath) as! firstVCCell

    return cell
}
}
Run Code Online (Sandbox Code Playgroud)

vac*_*ama 14

当组合UITabBarControllerUINavigationControllerS,以设置了正确的方法是使UITabBarControllerrootViewController.你的每个标签UITabBarController都有自己的标签UINavigationController.因此,如果您有4个选项卡,则将创建4个选项卡UINavigationControllers.

请参阅:将导航控制器添加到选项卡栏界面


更新

建立关你在更新的问题添加的代码,创建一个UINavigationController为每个的vc1,vc2vc3.

class CustomTabBarController: UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let vc1 = UINavigationController(rootViewController: FirstViewController())
        let vc2 = UINavigationController(rootViewController: SecondViewController())
        let vc3 = UINavigationController(rootViewController: ThirdViewController())

        viewControllers = [vc1, vc2, vc3]
    }

}
Run Code Online (Sandbox Code Playgroud)

在每个ViewControllers中,title选择该选项卡时,设置为要在导航栏中显示的标题:

class FirstViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .red
        title = "First"
        self.navigationController?.navigationBar.titleTextAttributes =
            [NSFontAttributeName: UIFont(name: "Chalkduster", size: 27)!,
             NSForegroundColorAttributeName: UIColor.black]
    }
}
Run Code Online (Sandbox Code Playgroud)