0

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 :)

GabrielaBezerra
  • 920
  • 11
  • 16
  • could you please show us your storyboard? which view controller you want to dismiss? because uivewcontroller and you want to dismiss it hard to understand – elk_cloner Jun 12 '17 at 03:49
  • Everything is programmatically done. I have this "MainScreen" which is a `UITabBarController`, with 4 items. At some point i place a `UIViewController` over this MainScreen using a modal segue (it's kinda like an action). When i dissmis it, i want to set another selectedIndex for the TabBar, but i can't find a way to do it. – GabrielaBezerra Jun 12 '17 at 03:59
  • When you dismiss your view controller, in completion you can't able to get the instance of the ViewController – Bala Jun 12 '17 at 04:41
  • I was trying to get the instance of the `UITabBarController` which called the `UIViewController` modally. I've found a solution to this, check my answer bellow. – GabrielaBezerra Jun 12 '17 at 05:01

3 Answers3

4

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
})
Naveed Ahmad
  • 6,627
  • 2
  • 58
  • 83
GabrielaBezerra
  • 920
  • 11
  • 16
1

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
    })
Bala
  • 1,224
  • 1
  • 13
  • 25
0

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
Srinivasan_iOS
  • 972
  • 10
  • 12