Swift中如何获取UITabBar选中项索引(非UITabBarController且无法用tag)
在Swift中获取UITabBar选中标签的索引(不依赖tag)
嘿,我明白你的痛点——UITabBarItem.tag已经被用来做别的事情了,没法靠它来获取选中标签的索引对吧?别担心,这里有几个直接从UITabBar本身入手的靠谱方法:
通过
selectedItem直接查找索引
你可以利用UITabBar的selectedItem属性,再结合它的items数组来定位选中项的位置。因为items数组的顺序和界面上标签的排列顺序完全一致,所以找到的索引就是你要的结果:// 假设你有一个UITabBar实例叫tabBar if let selectedItem = tabBar.selectedItem, let selectedIndex = tabBar.items?.firstIndex(of: selectedItem) { print("当前选中的标签索引是:\(selectedIndex)") }在UITabBar代理方法中实时获取
如果需要监听标签切换的动作,可以实现UITabBarDelegate的tabBar(_:didSelect:)方法,在用户点击标签时直接拿到选中项的索引:extension YourViewController: UITabBarDelegate { func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { guard let selectedIndex = tabBar.items?.firstIndex(of: item) else { return } print("用户切换到了索引为\(selectedIndex)的标签") } }
小提醒
- 记得先确保
tabBar.items不为空,所以用可选绑定来避免崩溃; - 如果之后动态修改了
items数组(比如添加/删除标签),这些方法依然有效,因为是基于当前的items数组来查找的。
内容的提问来源于stack exchange,提问作者Jaydeep Vyas
相关产品推荐
相关产品推荐

