如何在Dismiss之后以编程方式更改UITabBar选择的索引?

问题描述 投票:0回答:3

我在UIViewController上有一个模态UITabBarViewcontroller,我想解雇它,然后更改我的标签栏的选定项目。

我试图通过设置selectedIndex解雇'完成来完成它:

self.dismiss(animated: true, completion: {
    self.tabBarController?.selectedIndex = 2        
})

如果这是一个新手问题我很抱歉,我无法在任何地方找到解决方案。提前感谢您发给我的每个答案,线索或旧的类似问题:)

ios swift uikit uitabbarcontroller uitabbar
3个回答
2
投票

我能够通过在解除之前保存presentingViewController(称为模态segue的视图控制器)的引用来解决此问题,然后使用它在完成内部设置selectedIndex。像这样:

let referenceForTabBarController = self.presentingViewController as! UITabBarController
self.dismiss(animated: true, completion:{ 
     referenceForTabBarController.selectedIndex = 2
})

1
投票

视图控制器被关闭后执行完成块。这意味着您的视图不再显示在屏幕上。因此,您需要在完成块中创建新实例

self.dismiss(animated: true, completion: {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let tabBarController = appDelegate.window?.rootViewController as! UITabBarController
        tabBarController.selectedIndex = 2
    })

0
投票

如果你想把代码放在按钮动作或者为tableview或collectionview选择项目 - swift 4.2

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let tabBarController = appDelegate.window?.rootViewController as! UITabBarController
tabBarController.selectedIndex = 2
© www.soinside.com 2019 - 2024. All rights reserved.