Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在Swift中更改UITabBar selectedItem_Ios_Swift_Uitabbar_Swift2 - Fatal编程技术网

Ios 在Swift中更改UITabBar selectedItem

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

如何以编程方式更改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.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。我更新了我的答案,并相信你。对我来说,这个答案非常有效!