2016-04-25 1 views
0

私のアプリケーションのテンプレートを作成しようとしています...私のアプリケーションが4つのタブのCollectionViewを持つ同じビューコントローラーをロードすると言うことができます。選択したインデックスに応じて、コンテンツをコレクションビューにロードする必要があります。私はAppdelegateから手動でタブバーを設定しています。私の質問は、一度にTabbarcontrollerのすべての4つのタブに対して同じviewcntrollerをインスタンス化するようなことです。はいの場合、どのインデックスが選択されているかを正しく知る方法はありますか?4つのタブのタブバーコントローラーの同じView Controllerが誤って選択されたタブコントローラーの選択されたインデックスを与えています

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() 
+0

私は時々NSTimerと方法の変更を使用してそれを解決すると思うし、状態を取得するには、ここで説明するように、悪い状態を与える http://stackoverflow.com/questions/28099148/switch-tab-bar- programatically-in-swift – Saty

+0

クラスをタブバーコントローラのデリゲートとして設定すると、 'didSelectViewController'が呼び出されます。選択したビューコントローラを 'controllers'配列と比較して、選択したビューコントローラのインデックスを確認できます – Paulw11

+0

何か間違っていない限り、NSTimerは必要ありません。 – Paulw11

答えて

0

あなたのタブバーコントローラのデリゲートとしてクラスを設定する場合は、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 
    } 
}