How do I set selected tab in UITabBarController using StoryBoard?

前端 未结 10 1447
一整个雨季
一整个雨季 2020-12-31 00:38

How can I switch to some tab in UITabBarController using StoryBoard? I have tried the code below but without success (the tab is not selected):

         


        
相关标签:
10条回答
  • 2020-12-31 00:58

    Alexander, I think your problem is getting correct instance of your tab bar. If your tab bar is your root view controller, then you can do it like this in your appdelegate if didFinishLoading method:

    UITabBarController *tabBar = (UITabBarController *)self.window.rootViewController;
        [tabBar setSelectedIndex:3];
    

    Give it a try and tell me the result please.

    0 讨论(0)
  • 2020-12-31 00:58

    *Swift Comment - 18 months later if you convert Yanchi's solution into Swift in your appDelegate you'll get the expected result. The Swift translation is:

    let tabBar: UITabBarController = self.window?.rootViewController as! UITabBarController
    
    tabBar.selectedIndex = 1
    
    0 讨论(0)
  • 2020-12-31 00:58

    This will work in stroryboard too...

    [self.tabBarController setSelectedIndex:3]; with this add UITabBarControllerDelegate in .h

    and then use this delegate method

    - (BOOL)tabBarController:(UITabBarController *)theTabBarController shouldSelectViewController:(UIViewController *)viewController
    {
        return (theTabBarController.selectedViewController != viewController);
    }
    
    0 讨论(0)
  • 2020-12-31 00:59

    You can achieve this also using storyboards only. Ctrl-drag from the tabBarController to your ViewController(s), and select 'Relationship Segue, View controllers'. The first ViewController you select will be the default/initial ViewController.

    0 讨论(0)
  • 2020-12-31 01:00

    I'm using IBInspected in LSwift:

    extension UITabBarController {
        @IBInspectable var selected_index: Int {
            get {
                return selectedIndex
            }
            set(index) {
                selectedIndex = index
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-31 01:02

    You can also set the default tab in "User Defined Runtime Attributes" using storyboard.

    Select your Tab Bar Controller from storyboard, in the right pane select Identity Inspector and add an attribute:

    Key Path : selectedIndex
    Type     : Number
    Value    : 2 ( whatever number you want )
    
    0 讨论(0)
提交回复
热议问题