3

I'm looking for a way to find which tab bar item is select on my tab bar controller.

I've got 5 items and for one of them, I would like to show a "registration view" if the user is not logged in.

I've got all my verifications but I don't find the good way to check if the user tapped the fourth item on my tab bar.

Any ideas ? Thanks

self.tabBarController?.delegate = UIApplication.shared.delegate as? UITabBarControllerDelegate

        func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
            if viewController is CalculatorViewController {
                print("Redirect to register view")
            }

            return true
        }
noxo.
  • 116
  • 10

2 Answers2

1

You can try to use such thing (if you are using navigation controller, for sure)

override func viewDidLoad() {
    super.viewDidLoad()

    if let index = self.tabBarController?.selectedIndex, index == 3 {
         // do things here
    }

}

UPD. Or even like so

override func viewDidLoad() {
    super.viewDidLoad()

    if !userLogedIn {
         self.tabBarController?.selectedIndex = index // index is your tab bar item with login view
    }

}
Pete Streem
  • 360
  • 5
  • 14
0
 func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        guard let index = tabBarController.viewControllers?.firstIndex(where: {$0 === viewController}) else {
            return false
        }

        if index == 3 && !IS_LOGGED_IN{
            /*** show registration ***/
            return false //if you want to disable transition to the associated viewController against that tab
        }
        return true
 }
Umair
  • 1,203
  • 13
  • 15