tab bar did select delegate methods give the previously selected tab index in ios, swift 3

风格不统一 提交于 2019-12-07 05:55:21

问题


I'm trying to detect which tab selected by the user, realtime. as an example, if user selecte 0 th index, at the same time I want to get that user has selected the zeroth index tab. so for that , I used tabbarcontroller delegate method like below.

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

        print("the selected index is : \(selectedIndex)")
    }

but this shows the previous view controller.as an example think I'm in second tab and then I select the first tab then this prints the index as 2.so how can I get the correct selected tab. hope your help with this.


回答1:


You can get index of selected UITabBarItem by getting position of that particular item from array of items in UITabBar. Try this out

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    print("the selected index is : \(tabBar.items.index(of: item))")
}



回答2:


Swift 3.1:

 override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
     guard let items = tabBar.items else { return }
     print("the selected index is : \(String(describing: items.index(of: item)))")
}


来源:https://stackoverflow.com/questions/41436870/tab-bar-did-select-delegate-methods-give-the-previously-selected-tab-index-in-io

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!