用于4个选项卡的Tab栏控制器中的相同视图控制器提供了错误的选定tabcontroller选择索引

时间:2016-04-25 05:44:20

标签: ios swift tabs tabbarcontroller

我正在为我的应用程序制作一个模板...让我的应用程序加载相同的视图控制器,它有一个4个选项卡的CollectionView。根据选定的索引,我必须将内容加载到集合视图中。我正在从Appdelegate手动设置标签栏。我的问题是,这可能就像一次为Tabbarcontroller的所有4个选项卡实例化相同的viewcntroller一样。如果是,我将如何正确地知道选择了哪个索引?

Appdelegate中tabBarcontroller的代码

                self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
                let tabBarController = UITabBarController()

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

                let firstImage = UIImage(named: "image1")
                let secondImage = UIImage(named: "image2")
                var controllers = [UIViewController]()
                for var i = 0; i < self.myList.count; i++ {

                 let vc : ViewControllerTwo = storyboard.instantiateViewControllerWithIdentifier("view1") as! ViewControllerTwo

                    if(i == 0 || i == 3)
                    {
                        vc.tabBarItem = UITabBarItem(
                            title: self.myList[i],
                            image: firstImage,
                            tag: i)
                        controllers.append(vc)
                    }
                    else
                    {
                        vc.tabBarItem = UITabBarItem(
                            title: self.myList[i],
                            image: secondImage,
                            tag: i)
                        controllers.append(vc)
                    }


                }


                self.tabBarController.viewControllers = controllers
                self.window?.rootViewController = self.tabBarController


                self.self.window?.rootViewController = self.tabBarController
                self.window?.makeKeyAndVisible()

1 个答案:

答案 0 :(得分:2)

如果您将类设置为标签栏控制器的委托,则会调用didSelectViewController委托方法。然后,您可以使用controllers数组来确定索引;

self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let tabBarController = UITabBarController()
tabBarController.delegate = self


func tabBarController(_ tabBarController: UITabBarController,
   didSelectViewController viewController: UIViewController) {

    if let index = self.controllers.indexOf(viewController) {
        // Do something with index
    }
}