UITabBar控制器是否提供先前选择的索引?

Lea*_*awk 1 uitabbarcontroller ios swift

UITabBarController在应用程序中使用“自定义”来检查选定的索引。当我选择时,我会触发此方法selectedIndex

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

 //   print(self.selectedIndex)

    switch self.selectedIndex {
    case 1:

        print("should load feed " + String(self.selectedIndex))
        (self.viewControllers![1] as?  PageViewController)?.downloadNews()
   case 2:
        print("should load saved" + String(self.selectedIndex))
        (self.viewControllers![2] as? SavedController)?.loadData()
    default:
        return
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我单击新的标签栏项目时,会得到旧的选定索引。我知道这很容易。有没有办法在这种方法中取出正确的索引?

Lea*_*awk 6

selectedIndex直到didSelect发生才实际上没有改变。项目索引应取自项目本身。

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem)
{ 
   let indexOfTab = tabBar.items?.index(of: item)
   print("pressed tabBar: \(String(describing: indexOfTab))")
}
Run Code Online (Sandbox Code Playgroud)