如何在 Dismiss 后以编程方式更改 UITabBar 选定的索引?
How to programmatically change UITabBar selected index after Dismiss?
我在 UITabBarViewcontroller
上有一个模式 UIViewController
,我想关闭它,然后更改我的标签栏的选定项目。
我试图通过设置 selectedIndex
inside dismiss' completion 来完成它:
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
})
如果您想将代码放在按钮操作中或为表视图或集合视图选择项目 - swift 4.2
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let tabBarController = appDelegate.window?.rootViewController as! UITabBarController
tabBarController.selectedIndex = 2
我在 UITabBarViewcontroller
上有一个模式 UIViewController
,我想关闭它,然后更改我的标签栏的选定项目。
我试图通过设置 selectedIndex
inside dismiss' completion 来完成它:
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
})
如果您想将代码放在按钮操作中或为表视图或集合视图选择项目 - swift 4.2
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let tabBarController = appDelegate.window?.rootViewController as! UITabBarController
tabBarController.selectedIndex = 2