Minitour / AZTabBarController

A custom tab bar controller for iOS written in Swift 4.2
MIT License
348 stars 65 forks source link

equivalent func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) #17

Closed raphaels17 closed 7 years ago

raphaels17 commented 7 years ago

Hi

is there any way to access the current controller with AZtabbar delegate . I only find methods with the index. What I try to achieve is to reset the navigation when I tab on a given a tab. I understand removeViewController, will not move on the current index therefore I try to use an unwind segue but I need to access the controller that is being shown.

Any idea ?

Regards

Raphael

func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
    let index : Int = (tabBarController.viewControllers?.indexOf(viewController))!
    if index == 0 {
        let navigationController = viewController as? UINavigationController
        navigationController?.popToRootViewControllerAnimated(true)
    }

}
Minitour commented 7 years ago

@raphaels17 I can offer 2 solutions:

First solution is to modify AZTabBarController.swift:

Make the property public:

fileprivate var controllers: [UIViewController?]!

Change to

open var controllers: [UIViewController?]!

Second solution:

In your main controller (where you have an instance of AZTabBarController) keep a strong reference to your child view controllers:

//assuming ViewController is your main controller
class ViewController: UIViewController{

   var tabBar: AZTabBarController?
   var controllers: [UIViewController?] = []
   ...

  func viewDidLoad(){
        super.viewDidLoad()
        ...
        tabBar = AZTabBarController.insert(into: self, ...)
        tabBar.delegate = self
       //do additional setup

       let myFirstVC = FirstViewController()
       controllers.append(myFirstVC)
       tabBar.setViewController(myFirstVC, atIndex: 0)

       let secondVC = SecondViewController()
       controllers.append(secondVC)
       tabBar.setViewController(secondVC , atIndex: 1)

       //make sure, if you are adding an action to add nil to your array.
       controllers.append(nil)
       tabBar.setAction(atIndex 2){ ... }

       ...

}

extension ViewController: AZTabBarDelegate{
      func tabBar(_ tabBar: AZTabBarController, didSelectTabAtIndex index: Int){
            if let controller: UIViewController = controllers[index]{
                   //reset the navigation
            }
      }
}
raphaels17 commented 7 years ago

Thanks its works (tested solution 1)