Detect when a tab bar item is pressed

前端 未结 6 944
灰色年华
灰色年华 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 07:59

    Here is a version of @mbeaty's answer with a little more context. It is adapted from my fuller answer here.

    import UIKit
    
    class MyTabBarController: UITabBarController, UITabBarControllerDelegate {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // tell our UITabBarController subclass to handle its own delegate methods
            self.delegate = self
        }
    
        // called whenever a tab button is tapped
        func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
    
            if let firstVC = viewController as? FirstViewController {
                firstVC.doSomeAction()
            }
    
            if viewController is FirstViewController {
                print("First tab")
            } else if viewController is SecondViewController {
                print("Second tab")
            }
        }
    
        // alternate method if you need the tab bar item
        override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
            // ...
        }
    }
    

    Set this as the Custom class of your Tab View Controller in IB.

    Alternate solution

    • Just do something in the viewDidLoad method of the tab's view controller. See this answer.

提交回复
热议问题