How to programmatically change UITabBar selected index after Dismiss?

南笙酒味 提交于 2019-12-12 05:14:41

问题


I have a modal UIViewController over the UITabBarViewcontroller and i want to dismiss it, then change the selected item of my tab bar.

I'm trying to accomplish it by setting the selectedIndex inside dismiss' completion:

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

I apologize if this is a newbie question, i just couldn't find the solution to this anywhere. Thanks in advance for every answer, clue or old similar questions that you send me :)


回答1:


I was able to solve this problem by saving the reference of the presentingViewController (the view controller who called the modal segue) before the dismiss, and then using it to set the selectedIndex inside the completion. Like this:

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



回答2:


The completion block is executed after the View Controller has been dismissed. This means your view is no longer on screen. So you need to create new instance with in the completion block

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



回答3:


if you want put the code in button action or didselect item for tableview or collectionview - swift 4.2

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let tabBarController = appDelegate.window?.rootViewController as! UITabBarController
tabBarController.selectedIndex = 2


来源:https://stackoverflow.com/questions/44491118/how-to-programmatically-change-uitabbar-selected-index-after-dismiss

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!