gpt4 book ai didi

ios - UINavigationController 和 TabBarController 以编程方式(无 Storyboard)

转载 作者:搜寻专家 更新时间:2023-11-01 05:45:48 26 4
gpt4 key购买 nike

目前,我的 AppDelegate 文件包含将 CustomTabBarController 设置为 rootViewController 的代码:

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

我希望我的应用始终在底部具有 CustomTabBarController,但我希望每个选项卡都有一个导航 Controller 。这是我用来设置 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
}
}

最佳答案

当组合 UITabBarControllerUINavigationController 时,设置它的正确方法是使 UITabBarController 成为 rootViewControllerUITabBarController 的每个选项卡都有自己的 UINavigationController。因此,如果您有 4 个选项卡,您将创建 4 个 UINavigationControllers

参见:Adding a Navigation Controller to a Tab Bar Interface


更新

根据您在更新后的问题中添加的代码,为您的每个 vc1vc2 创建一个 UINavigationController >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]
}
}

关于ios - UINavigationController 和 TabBarController 以编程方式(无 Storyboard),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43961766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com