Prevent screen change when I press tab which is already selected

36 views Asked by At

I have a CustomTabBarController with 4 tabs. When I am inside the 3rd tab, let's say I have a screen called A and I have a button which takes me a second screen called B. So, when I am on screen B and I am pressing the 3rd tab, I want to stay on screen B. The current app behaviour is when I am on screen B and I am pressing the 3rd tab, the app navigates to screen A.

Do you know how to solve this issue?

1

There are 1 answers

0
clawesome On BEST ANSWER

In your CustomTabBarController subclass inherit the UITabBarControllerDelegate protocol and in your viewDidLoad() set your controller's delegate to self. Then override the func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool method returning false if the current selectedViewController equals the passed in view controller.

class CustomTabBarController: UITabBarController, UITabBarControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.delegate = self
    }
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        if selectedViewController == viewController {
            return false
        }
        return true
    }
    
}