Search code examples
iosswifttabsnavigationbartabbar

Swift: Setting Different Navigation Bar Buttons for Different Tabs


I created a custom UITabBarController with 5 tabs in Swift 3.0. I've been trying to set different navigation bar items for certain tabs, but it's not working well.

Situation: I put codes that would change the Navigation Bar Buttons in each tab's viewDidLoad().

//The customized Tab Bar controller instance. Contained in each of the tabs.
var mainController: TabBarController?

override func viewDidLoad() {
    // ... more code
    setupNavBar()
    // ... more code
}

func setupNavBar() {
    // ... more code
    mainController?.navigationItem.leftBarButtonItem = UIBarButtonItem(image: friendsImage, style: .plain, target: self, action: #selector(handleFindFriends))
    // ... more code
}

Problem: Let's say Tab #1 is supposed to have NavBarButton A and Tab #2 is supposed to have NavBarButton B. When I switch from Tab #1 to Tab #2, the code works fine; the NavBarButton changes from A to B. However, when I click on Tab #1, the NavBarButton still remains B.

How can I make it so that the navigation bar buttons change accordingly even when I click on a tab I was on previously?


Solution

  • I actually found a solution XD In TabBarController:

    override func viewWillAppear(_ animated: Bool) {
        //Original code to set up tabs
    
        //Code I added:
        for i in 0...4 {
            tabBar.items?[i].tag = i
        }
    }
    //Code I added:
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        //Code to run when a certain tab is selected
    }
    

    Still, thanks a lot!