以编程方式将NavigationController添加到基于TabBar的应用程序

时间:2018-08-14 22:01:43

标签: ios swift uinavigationcontroller uitabbarcontroller

我在基于customTabBar的应用程序中有6个viewControllers。 TabbBar以编程方式添加。 现在,我想添加一个navigationcontroller,以推动详细信息视图控制器从navigationBar中获得好处,但将TabBar保留为在整个应用中进行导航的主要方式。

使用此代码,我获得了第一个uiviewcontroller“ FirstVC”,它具有屏幕上的导航栏,但是我无法从测试按钮“推”详细信息“ FirstDetail1VC”视图控制器

在我的AppDelegate中:

window = UIWindow(frame: UIScreen.main.bounds)

let myTabController = CustomTabbarController()

window?.rootViewController = myTabController
window?.makeKeyAndVisible()

在my1VC中(给出消息“无法推送UINavigationController”):

func showNextVc() {

    let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    if let newViewController = storyboard.instantiateViewController(withIdentifier: "FirstDetail1VC") as? FirstDetail1VC {

        let navigator = MyMainNavController {
            navigator.pushViewController(newViewController, animated: true)
        }
    }
}

在CustomTabbarController中更新后:

let storyboard = UIStoryboard(name: "Main", bundle: nil)

let my1VC = storyboard.instantiateViewController(withIdentifier: "FirstVC")
let my2VC = storyboard.instantiateViewController(withIdentifier: "SecondVC")
let my3VC = storyboard.instantiateViewController(withIdentifier: "ThirdVC")
let my4VC = storyboard.instantiateViewController(withIdentifier: "FourthVC")
let my5VC = storyboard.instantiateViewController(withIdentifier: "FifthVC")
let my6VC = storyboard.instantiateViewController(withIdentifier: "SixthVC")

my2VC.tabBarItem = UITabBarItem(title: "second", image: nil, selectedImage: nil)
my3VC.tabBarItem = UITabBarItem(title: "third", image: nil, selectedImage: nil)
my4VC.tabBarItem = UITabBarItem(title: "fourth", image: nil, selectedImage: nil)
my5VC.tabBarItem = UITabBarItem(title: "fifth", image: nil, selectedImage: nil)
my6VC.tabBarItem = UITabBarItem(title: "sixth", image: nil, selectedImage: nil)

let controllers = [my1VC, my2VC, my3VC, my4VC,my5VC, my6VC]


// if I use this one, text titles appears on tab bar, but cannot use navigation controller
viewControllers = controllers

// if I use this I have the navigation controlelr working but     
tabBarbuttons not showing text title
// self.viewControllers = controllers.map {
// UINavigationController(rootViewController: $0)
// }

1 个答案:

答案 0 :(得分:1)

在设置所有ViewController的数组时,将UINavigationController分配给每个UIViewController。

//Add NavigationController to all VC
viewControllers = [start, my1VC, my2VC, my3VC, my4VC,my5VC, my6VC].map {
    UINavigationController(rootViewController: $0)
}