目前,我的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
}
}
答案 0 :(得分:11)
合并UITabBarController
和UINavigationController
时,正确设置方法是将UITabBarController
设为rootViewController
。 UITabBarController
的每个标签都有自己的UINavigationController
。因此,如果您有4个标签,则会创建4个UINavigationControllers
。
请参阅:Adding a Navigation Controller to a Tab Bar Interface
<强>更新强>
根据您在更新后的问题中添加的代码,为每个UINavigationController
,vc1
和vc2
创建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)}