问题
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