我在UIViewController
上有一个模态UITabBarViewcontroller
,我想解雇它,然后更改我的标签栏的选定项目。
我试图通过设置selectedIndex
解雇'完成来完成它:
self.dismiss(animated: true, completion: {
self.tabBarController?.selectedIndex = 2
})
如果这是一个新手问题我很抱歉,我无法在任何地方找到解决方案。提前感谢您发给我的每个答案,线索或旧的类似问题:)
我能够通过在解除之前保存presentingViewController
(称为模态segue的视图控制器)的引用来解决此问题,然后使用它在完成内部设置selectedIndex。像这样:
let referenceForTabBarController = self.presentingViewController as! UITabBarController
self.dismiss(animated: true, completion:{
referenceForTabBarController.selectedIndex = 2
})
视图控制器被关闭后执行完成块。这意味着您的视图不再显示在屏幕上。因此,您需要在完成块中创建新实例
self.dismiss(animated: true, completion: {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let tabBarController = appDelegate.window?.rootViewController as! UITabBarController
tabBarController.selectedIndex = 2
})
如果你想把代码放在按钮动作或者为tableview或collectionview选择项目 - swift 4.2
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let tabBarController = appDelegate.window?.rootViewController as! UITabBarController
tabBarController.selectedIndex = 2