Programmatically switching between tabs within Swift

后端 未结 8 542
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 02:32

I need write some code to switch the view to another tab when the iOS app starts (so, for example, the second tab is shown by default rather than the first).

I\'m ne

8条回答
  •  渐次进展
    2020-11-30 03:26

    If your window rootViewController is UITabbarController(which is in most cases) then you can access tabbar in didFinishLaunchingWithOptions in the AppDelegate file.

    func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
        // Override point for customization after application launch.
    
        if let tabBarController = self.window!.rootViewController as? UITabBarController {
            tabBarController.selectedIndex = 1
        }
    
        return true
    }
    

    This will open the tab with the index given (1) in selectedIndex.

    If you do this in viewDidLoad of your firstViewController, you need to manage by flag or another way to keep track of the selected tab. The best place to do this in didFinishLaunchingWithOptions of your AppDelegate file or rootViewController custom class viewDidLoad.

提交回复
热议问题