Detect when a tab bar item is pressed

前端 未结 6 960
灰色年华
灰色年华 2020-11-28 07:37

I have a root view controller which isn’t set as the custom class for any of my view controllers on my storyboard. Instead, all of my view controllers are subclassing this c

6条回答
  •  天涯浪人
    2020-11-28 08:01

    I used this code, because I need to know that the same view controller is selected.

    import UIKit
    
    protocol CustomTabBarControllerDelegate {
        func onTabSelected(isTheSame: Bool)
    }
    
    class CustomTabBarController: UITabBarController, UITabBarControllerDelegate {
        override func viewDidLoad() {
            super.viewDidLoad()
            self.delegate = self
        }
        
        func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
            (viewController as? CustomTabBarControllerDelegate)?.onTabSelected(isTheSame: selectedViewController == viewController)
            return true
        }
    }
    

    First tab view contoller

    import UIKit
    
    class Tab1ViewController: UIViewController, CustomTabBarControllerDelegate {
        func onTabSelected(isTheSame: Bool) { 
            print("Tab1ViewController onTabSelected")
            //do something
        }
    }
    

    Second tab view contoller

    import UIKit
    
    class Tab2ViewController: UIViewController, CustomTabBarControllerDelegate {
        func onTabSelected(isTheSame: Bool) { 
            print("Tab2ViewController onTabSelected")
            //do something
        }
    }
    

    Don't forget to set CustomTabBarController as custom class to your TabBarController in your storyboard and to implement CustomTabBarControllerDelegate protocol by all your tab view controllers.

    If you use UINavigationController it can not work if UINavigationController is not storyboard entry point. Make sure that you have storyboard structure like below.

提交回复
热议问题