SwiftUI 点击标签栏时如何为所有图标添加动画而非仅单个生效
问题解决方法
你当前动画仅对通知铃铛生效的核心原因是动效触发条件硬编码了仅匹配"Notifications"标签的条目,和if/switch选型没有直接关系。
方案1:所有图标统一使用相同旋转动效(无需改用switch)
直接调整动效判断条件,只要当前项处于选中状态就触发旋转即可,优化后代码如下:
if selection == index { Color(.label) .frame(height: 2) .offset(y: -8) .matchedGeometryEffect(id: "currentTab", in: currentTab) // 选中状态下所有图标都应用旋转动效 Image(systemName: tabs[index].image) .frame(height: 20) .rotationEffect(.degrees(25)) } else { // 未选中状态使用默认样式 Image(systemName: tabs[index].image) .frame(height: 20) .rotationEffect(.degrees(0)) } Text(tabs[index].label) .font(.caption2) .fixedSize() .foregroundColor(.blue) // 后续原有代码保持不变 .fixedSize(horizontal: false, vertical: true) .frame(width: geometry.size.width / 2, height: 44, alignment: .bottom).padding(.horizontal).foregroundColor(selection == index ? Color(.label) : .secondary ) .onTapGesture{ withAnimation{selection = index} }
修改后所有标签项被选中时,都会触发和通知铃铛一致的旋转动画。
方案2:如需给不同图标配置差异化动效,可改用switch
如果后续要给不同图标设置不同的选中动效(比如通知旋转、首页缩放、个人中心偏移),使用switch语句会更易维护,示例代码如下:
if selection == index { Color(.label) .frame(height: 2) .offset(y: -8) .matchedGeometryEffect(id: "currentTab", in: currentTab) // 按标签类型匹配对应动效 switch tabs[index].label { case "Notifications": Image(systemName: tabs[index].image) .frame(height: 20) .rotationEffect(.degrees(25)) case "Home": Image(systemName: tabs[index].image) .frame(height: 20) .scaleEffect(1.2) default: Image(systemName: tabs[index].image) .frame(height: 20) .offset(y: -3) } } else { Image(systemName: tabs[index].image) .frame(height: 20) // 未选中状态重置所有动效参数 .rotationEffect(.degrees(0)) .scaleEffect(1) .offset(y: 0) }

内容的提问来源于stack exchange,提问作者MACHINE666
相关产品推荐
相关产品推荐

