如何在非UIView类中切换uiViews

时间:2016-05-20 07:23:48

标签: ios swift uitabbarcontroller uitabbar selectedindex

所以这就是情况。我有一个应用程序,它提供了一个tabBarController作为其根视图控制器,具有许多tabItems。所以这是我的app delegate中的设置

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        let vc1 = VC1(nibName: "VC1", bundle: nil)
        let vc2 = VC2(nibName: "VC2", bundle: nil)

        let menuTabBarController = MenuTabBarController(nibName: "MenuTabBarController", bundle: nil)
        menuTabBarController.viewControllers = [VC1,VC2]

        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.rootViewController = menuTabBarController
        window?.makeKeyAndVisible()

        //Setup tab bar
        UITabBar.appearance().barTintColor = UIColor.blackColor()

        let IMG1 = UIImage(named: "img2.png")
        let IMG2 = UIImage(named: "img2.png")

        VC1.tabBarItem = UITabBarItem(
        title: "View 1",
            image: IMG1,
            tag: 1)
        VC2.tabBarItem = UITabBarItem(
            title: "View 2",
            image: IMG2,
            tag:2)



        return true
    }

    func applicationWillResignActive(application: UIApplication) {

    }

    func applicationDidEnterBackground(application: UIApplication) {

    }


}

请注意,我在menuTabBar中嵌套了两个UIViewController类(VC1和VC2)。现在从menuTabBar类,我可以轻松切换视图,如此

    class MenuTabBarController: UITabBarController,UITabBarControllerDelegate{

        override func viewDidLoad() {
            super.viewDidLoad()

            self.delegate = self//Set tabbarcontroller delegate

        }

        // UITabBarControllerDelegate
        func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
            tabBarController.selectedIndex = 1;//Say I wanted to transition to VC2
        }

    }

但我最终想做的是能够在另一个不是UIViewController的类之间切换两个UIViewControllers。我试过这样的事情

    class Actions(){
        func someFunctionThatSwitchesToVC2(){
            //So I create a reference to appDelegate which in turn, is supposed to reference the tab bar and switch between its child views

            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

            let tabBarController: UITabBarController = (appDelegate.window?.rootViewController as? UITabBarController)!
            tabBarController.selectedIndex = 1
        }
    }

当我运行someFucntionThatSwitchesToVC2时,我收到此错误“致命错误:索引超出范围”。显然我做的不对。任何想法都非常感激 PS,当我做tabBarController.selectedIndex = 0时,我没有得到错误但没有发生

1 个答案:

答案 0 :(得分:0)

我认为你在分配ViewControllers时正在做错字。改变这一行:

menuTabBarController.viewControllers = [VC1,VC2]

以下行:

menuTabBarController.viewControllers = [vc1,vc2]
相关问题