首页 > 解决方案 > 如何快速检查从 MDCTabBarView 中选择了哪个选项卡

问题描述

我已经设置了 MDCTabBarView 和 MDCTabBarViewDelegate,但是当我点击选项卡栏项目之一时,代表不起作用并打印数据。我的代码:

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")
    }
}

}

当我点击其中一个选项卡栏项目时,它确实起作用并更改了选项卡,但没有调用代理。我怎样才能让委托工作,以便我可以打印用户选择的选项卡?

标签: iosswift

解决方案


delegate为 工作MDCTabBarView,您必须添加tabBarView.tabBarDelegate = self并且必须删除shouldSelectshouldBeginMultipleSelectionInteractionAt方法,因为它不是方法,tabBarDelegate并且didSelect委托 mehtod 将起作用。


推荐阅读