标签栏上的选定索引在Swift上不起作用

时间:2019-06-05 05:31:51

标签: ios swift uitabbarcontroller uitabbaritem

我想更改Tab Bar的默认选定视图控制器。我尝试了在其他线程中看到的其他解决方案,例如在AppDelegateViewDidAppear中进行如下更改:

class MainTabBarController: UITabBarController {

  override func viewDidLoad() {
     super.viewDidLoad()

       setupTabBar()
    }

      /// this is the attempt to set the selected index that doesn't work 
  override func viewDidAppear(_ animated: Bool) {

     self.tabBarController?.selectedIndex = 2

    }

  func setupTabBar(){

    let vc1 = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "mainvc")
    let vc2 = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "secondvc")
    let vc3 = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "thirdvc")
    let FirstController = UINavigationController(rootViewController: vc1)
    let SecondController = UINavigationController(rootViewController: vc2)
    let ThirdController = UINavigationController(rootViewController: vc3)

    viewControllers = [FirstController, SecondController, ThirdController]

    }
}

到目前为止没有任何操作,它始终显示所选索引=0。

我在Main storyboard中将标签栏视图控制器设置为初始视图控制器。我应该在AppDelegate中这样做吗?

1 个答案:

答案 0 :(得分:2)

你是在说

class MainTabBarController: UITabBarController {

所以self指的是UITabBarController,但是您正在设置tabBarController的选定索引 of self

self.tabBarController?.selectedIndex = 2

self中没有嵌入标签栏控制器。 self本身标签栏控制器!您可以只设置self.selectedIndex

self.selectedIndex = 2

此外,您应该在viewDidLoad而不是viewDidAppear中这样做,因为viewDidAppear可能发生多次(例如,每次关闭某些模态控制器时)。 viewDidLoad只会被调用一次。