Chao Peng
Chao Peng

Reputation: 97

How to detect tab bar index changes in swift?

I have 3 tabs in a Tab Bar Controller: Main, TabOne, TabTwo(tab index 0,1,2 respectively)

Main view controller has a table view will show all the elements in a an array. In view controllers TabOne and TabTwo, they all have buttons:

@IBAction func mypost(_ sender: Any) {
    tabBarController?.selectedIndex = 0}

The array in Main view controller should be changed differently based on the tab index of the previous view controller. Ex. If the previous view controller is TabTwo, then the table view will only show all the elements of even indices BUT If the previous view controller is TabOne, then the table view will only show all the elements of odd indices

How can I do it?

Upvotes: 0

Views: 3210

Answers (1)

rmaddy
rmaddy

Reputation: 318904

One possible solution is to have your main view controller set itself up as the delegate of the tab bar controller. Then implement the delegate method shouldSelect and look at the tab controller's currently selected index.

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool
    let index = tabBarController.selectedIndex
    if index == 1 {
        // load data appropriate for coming from the 2nd tab
    } else index == 2 {
        // load data appropriate for coming from the 3rd tab
    }

    return true
}

Upvotes: 1

Related Questions