IskandarH
IskandarH

Reputation: 99

How to check which tab is selected from MDCTabBarView in swift

I already setup MDCTabBarView and MDCTabBarViewDelegate, but when i tap one of the tab bar item the delegate did not work and print the data. My code:

let tabBarView = MDCTabBarView()
    tabBarView.delegate = self
    tabBarView.items = [
        UITabBarItem(title: "Menu 1", image: nil, tag: 0),
        UITabBarItem(title: "Menu 2", image: nil, tag: 1),
        UITabBarItem(title: "Menu 3", image: nil, tag: 2),
        UITabBarItem(title: "Menu 4", image: nil, tag: 3),
        UITabBarItem(title: "Menu 5", image: nil, tag: 4),
    ]
    tabBarView.selectedItem = tabBarView.items[0]
    tabBarView.barTintColor = .brown
    tabBarView.preferredLayoutStyle = .scrollableCentered
    tabBarView.setTitleColor(.white, for: .normal)
    tabBarView.selectionIndicatorStrokeColor = .white
    view.addSubview(tabBarView)

extension ViewController: MDCTabBarViewDelegate {    
func tabBarView(_ tabBarView: MDCTabBarView, didSelect item: UITabBarItem) {
    print("item: \(item)")
    print("item.title: \(item.title)")
    if item.tag == 0 {
        print("item tag 0")
    }
    else if item.tag == 1 {
        print("item tag 1")
    }
    else if item.tag == 2 {
        print("item tag 2")
    }
    else if item.tag == 3 {
        print("item tag 3")
    }
    else if item.tag == 4 {
        print("item tag 4")
    }
}

}

When i tap one of tab bar item it did work and changed tab but not calling the delegate. How can i make the delegate work so i can print which tab is selected by the user?

Upvotes: 0

Views: 415

Answers (1)

Kishan Bhatiya
Kishan Bhatiya

Reputation: 2368

For delegate to work for MDCTabBarView, you have to add tabBarView.tabBarDelegate = self and you have to remove shouldSelect and shouldBeginMultipleSelectionInteractionAt method because it's not method for tabBarDelegate and didSelect delegate mehtod will work.

Upvotes: 2

Related Questions