iOS Swift:LazyVGrid的easeInOut动画value参数设置疑问
解决LazyVGrid动画的value参数问题
你需要把.animation(.easeInOut, value: ??)中的??替换为selectedLayoutType——动画的触发逻辑是布局类型切换:当selectedLayoutType改变时,LazyVGrid的columns会同步变化,绑定这个值就能让系统感知到布局变更,触发过渡动画。
iOS 15之后,SwiftUI要求显式指定动画的依赖值(即value参数),目的是明确触发动画的时机,避免旧版隐式动画可能导致的意外行为。
修改后的完整代码如下:
struct MysegmentView: View { var dummyDataArray = MyModel.dummyDataArray @State var selectedLayoutType : LayoutType = .table var body: some View { VStack{ Picker(selection: $selectedLayoutType, label: Text(".."), content: { ForEach(LayoutType.allCases, id: \.self, content: { layoutType in switch layoutType{ case .table: Image(systemName: "list.dash") case .grid: Image(systemName: "rectangle.grid.2x2") case .triple: Image(systemName: "circle.grid.3x3") } }) }).pickerStyle(SegmentedPickerStyle()) ScrollView{ LazyVGrid(columns: selectedLayoutType.columns, content: { ForEach(dummyDataArray) { dataItem in Rectangle().frame(height: 100) } }).animation(.easeInOut, value: selectedLayoutType) // 替换为selectedLayoutType } } } } // 补充LayoutType的示例定义(确保columns返回对应布局的GridItem数组) enum LayoutType: CaseIterable { case table, grid, triple var columns: [GridItem] { switch self { case .table: return [GridItem(.flexible())] // 单列布局 case .grid: return Array(repeating: GridItem(.flexible()), count: 2) // 2列网格 case .triple: return Array(repeating: GridItem(.flexible()), count: 3) // 3列网格 } } }
另外要确保LayoutType枚举的columns属性正确返回对应数量的GridItem,这样切换分段控件时布局才会产生变化,动画才能正常生效。
内容的提问来源于stack exchange,提问作者Jae
相关产品推荐
相关产品推荐

