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

时间:2017-05-14 08:12:21

标签: ios swift xcode swift3 xcode8

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

window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = CustomTabBarController()

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

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

以下是我用来设置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
}
}

2 个答案:

答案 0 :(得分:11)

合并UITabBarControllerUINavigationController时,正确设置方法是将UITabBarController设为rootViewControllerUITabBarController的每个标签都有自己的UINavigationController。因此,如果您有4个标签,则会创建4个UINavigationControllers

请参阅:Adding a Navigation Controller to a Tab Bar Interface

<强>更新

根据您在更新后的问题中添加的代码,为每个UINavigationControllervc1vc2创建vc3

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]
    }

}

在每个ViewController中,选择该标签后,将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]
    }
}

答案 1 :(得分:0)

你可能想试试这个:

viewControllers = [vc1, vc2, vc3].map{UINavigationController(rootViewController: $0)}