在 swift 中设置 UITabBar 中的默认选项卡

Setting default tab in UITabBar in swift

我几乎完成了一个项目,正在解决最后几个 UI 问题。我的应用程序使用选项卡栏进行导航,出于美观目的,我希望应用程序在最后一个选项卡(用户配置文件)而不是第一个选项卡上打开。我知道我可以在 Interface Builder 中重新排序选项卡,但是选项卡栏看起来很奇怪,首先是配置文件选项卡,然后是其他任何地方的主页选项卡。如何将配置文件选项卡保留为第 5 个选项卡,但默认情况下在该选项卡上打开应用程序?

只需设置tabBarController的selectedIndex即可。沿着这些路线的东西。

var freshLaunch = true
override func viewWillAppear(animated: Bool) {
     if freshLaunch == true {
         freshLaunch = false
         self.tabBarController.selectedIndex = 4 // 5th tab
     }
}

有一种很好的方法可以直接从 选项卡栏控制器 上的界面构建器执行此操作,单击 身份检查器 ,然后设置用户定义的运行时属性

在这种情况下,标签栏控件的每个索引都像从 0 开始的数组一样被索引。所以最左边是0,右边是1,然后是2等等...

所以在我的例子中,我希望首先选择 'tasks',因此您将 selectedIndex 设置为类型 Number 和值“1”。参考我附上的图片。

在第一项视图控制器中写入

tabBarController?.selectedIndex = 2//required value

如果您使用的是 UIStoryBoard 中的 UISegue,您可以在 UIViewController 中执行 UISegue

时使用它
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let tabBarController = segue.destination as? UITabBarController
    tabBarController?.selectedIndex = 1
}

class TabBarController: UITabBarController {

   override func viewDidLoad() {
       super.viewDidLoad()
       self.selectedIndex = 1
   }

}

此代码在您 UITabBarController 本身。