Ios 在Swift中更改UITabBar selectedItem
如何以编程方式更改UITabBar中的选定项?Swift 3及更高版本 从Swift 3开始,您还可以使用Ios 在Swift中更改UITabBar selectedItem,ios,swift,uitabbar,swift2,Ios,Swift,Uitabbar,Swift2,如何以编程方式更改UITabBar中的选定项?Swift 3及更高版本 从Swift 3开始,您还可以使用 tabBarController.selectedIndex = 0 // (or any other existing index) (谢谢你,@nidomiro。) Swift 2.2及更早版本 试试下面的方法 tabBar.selectedItem = tabBar.items![newIndex] as! UITabBarItem self.selectedViewContr
tabBarController.selectedIndex = 0 // (or any other existing index)
(谢谢你,@nidomiro。)
Swift 2.2及更早版本 试试下面的方法
tabBar.selectedItem = tabBar.items![newIndex] as! UITabBarItem
self.selectedViewController = self.viewControllers![newIndex] as! UIViewController
tabBarController.selectedViewController = tabBarController.viewControllers![newIndex] as! UIViewController
假设您有权访问拥有UITabBar
的UITabBar控制器
,您可以执行以下操作
tabBar.selectedItem = tabBar.items![newIndex] as! UITabBarItem
self.selectedViewController = self.viewControllers![newIndex] as! UIViewController
tabBarController.selectedViewController = tabBarController.viewControllers![newIndex] as! UIViewController
上面的代码行应该放在UITabBarController
子类中的某个位置
但是,如果您可以从“外部”访问选项卡栏控制器,请执行以下操作
tabBar.selectedItem = tabBar.items![newIndex] as! UITabBarItem
self.selectedViewController = self.viewControllers![newIndex] as! UIViewController
tabBarController.selectedViewController = tabBarController.viewControllers![newIndex] as! UIViewController
Swift 5及更高版本
我收到此错误:由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因是:“不允许直接修改由选项卡栏控制器管理的选项卡栏。
UITabBar
是否由UITabBarController
所有?”?如果是这样的话,你能找到它的参考资料吗?太好了!我很高兴能帮上忙。我修改了我的答案。我将其更新为使用强制向下投射操作符as代码>,这是Swift 2语法。在Swift 3中,以下内容对我有效:tabBarController.selectedIndex=0(或任何其他现有索引)谢谢@nidomiro。我更新了我的答案,并相信你。对我来说,这个答案非常有效!