Swift中MDCTabBarView如何获取选中标签?代理didSelect不触发
MDCTabBarView 代理不触发的修复方案
1. 修正协议方法签名(核心必改项)
你当前混淆了系统原生 UITabBar 和 MDC 组件 MDCTabBarView 的代理方法签名,这是代理不触发的直接原因:
- 系统
UITabBar的代理方法为tabBar(_:didSelect:) MDCTabBarViewDelegate要求的方法签名为tabBarView(_:didSelectItem:)
你实现的方法少了参数标签中的 Item 字段,Swift 运行时无法将其识别为协议要求的实现,因此即使设置了 delegate 也不会触发回调。同时这也能解释为什么选中状态可以正常切换:视图内部的选中样式更新逻辑独立于代理回调,只要接收点击就会自动完成状态切换。
修复后的代理实现代码:
extension ViewController: MDCTabBarViewDelegate { // 修正参数标签:将 didSelect 改为 didSelectItem func tabBarView(_ tabBarView: MDCTabBarView, didSelectItem item: UITabBarItem) { print("item: \(item)") print("item.title: \(item.title)") switch item.tag { case 0: print("item tag 0") case 1: print("item tag 1") case 2: print("item tag 2") case 3: print("item tag 3") case 4: print("item tag 4") default: break } } }
2. 修复潜在的内存持有隐患
你当前将 tabBarView 定义为方法内的局部常量,虽然添加为子视图后会被父视图强持有、暂时不会出现内存问题,但这种写法存在风险:如果后续代码主动将 tabBarView 从父视图移除,会因为无强引用导致对象被意外释放。
推荐将 tabBarView 提升为 ViewController 的实例属性,和控制器生命周期对齐
class ViewController: UIViewController { // 替换原有局部变量,作为实例属性持有 let tabBarView = MDCTabBarView() override func viewDidLoad() { super.viewDidLoad() // 原有配置逻辑保持不变 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) // 补充Auto Layout约束,避免frame计算异常导致点击区域失效 tabBarView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ tabBarView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tabBarView.trailingAnchor.constraint(equalTo: view.trailingAnchor), tabBarView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) ]) } }
内容的提问来源于stack exchange,提问作者IskandarH
相关产品推荐
相关产品推荐

