Search code examples
iosswiftuitabbarcontrolleruitabbaritem

Swift 4 - How to override tab bar will open view controller


Is it possible that when a user clicks on a Tab bar item that I can override this in the UITabBarController , where I then check a UserDefault which then decides whether I show the view or return and they stay on their current view ?

It would be something like this:

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    if item.image == UIImage(named: "TabProfile")
    {
        // Profile tab selected
        if !loginController.isUserLogged()
        {
            // Not logged in...
            showLoginView()  

            // Following line doesn't work...
            tabBarController?.selectedIndex = selectedIndex
        }
    }
}

If possible I want to perform this check and if false then actually prevent the view from even reaching viewDidLoad.

Thanks.


Solution

  • I guess you need

    func tabBarController(_ tabBarController: UITabBarController, 
                  shouldSelect viewController: UIViewController) -> Bool {
       if let ind = tabBarController.viewControllers!.index(of:viewController) , ind == 2 { // suppose profile is 2
          // 
           if userNotLogged { 
             // present modal login view 
             return false
           } 
       } 
      return true
    }