swift tabBarController selectedIndex 不工作

swift tabBarController selectedIndex not working

如何在具有 5 个以上视图控制器的标签栏控制器上手动调用标签索引?

我正在尝试手动调用选项卡索引,但它似乎不起作用。我有一个带有 6 个视图控制器的 tabview 控制器。我正在使用 selectedIndex 调用特定选项卡。在 iPhone 上,这适用于前 4 个选项卡,但不适用于选项卡 5 和 6。它在 iPad 上工作正常。

这是我正在使用的:

let getViewController = self.storyboard?.instantiateViewController(withIdentifier: "tabBar") as! UITabBarController
getViewController.selectedIndex = 5
self.navigationController?.present(getViewController, animated: true)

这会导致标签栏显示第一个标签,而不是预期的第 6 个标签。由于它在 iPad 上工作正常,我假设 "More" 选项卡使 tabindex 无法工作

如有任何帮助,我们将不胜感激!

调用 selectedViewController 而不是 selectedIndex

可能因为视图还没有加载,所以IBOutlets和子视图控制器还没有设置。

您可以在设置 selectedIndex 之前尝试调用 getViewController.loadViewIfNeeded()。或者创建一个扩展 UITabBarController 的 class 并在 viewDidLoad 中设置所需的 selectedIndex

我今天一直在使用 UITabBarController 并且 selectedIndex 使用没有任何问题。