Reputation: 126
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
}
Upvotes: 3
Views: 1783
Reputation: 390
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
}
}
Upvotes: 1
Reputation: 1253
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
}
Upvotes: 0