SwiftUI LazyVGrid 过渡动画不符合预期

ska*_*ber 3 macos ios swiftui lazyvgrid

我有一个 LazyVGrid,其定义如下:

let column = Array(repeating: GridItem(.flexible(minimum: 120, maximum: .infinity)), count: 3)
        
LazyVGrid(columns: column, alignment: .leading, spacing: 5) {
    ForEach(data, id: \.self.uniqueStableId) { _ in
        Color.red
             .transition(.move(edge: .trailing))
             .frame(height: 150)
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个按钮,可以启动动画效果:

func handleButtonTap() {
    for index in 0..<9 {
        DispatchQueue.main.asyncAfter(deadline: .now() + Double(1 * index)) {
            withAnimation(.easeInOut(duration: 1)) {
                let newItem = Item()
                self.data.append(newItem)                                                                                     
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

动画应使用幻灯片效果以 1 秒的间隔将新的红色方块一一添加到网格中,但存在 2 个问题:

  1. 即使我为红色视图设置了特定的过渡,该过渡也会被忽略,并且会添加带有淡入效果的方块

图片1

  1. 每次将行中的第一个方块添加到网格上的新行中时,它会从行的中间出现,并开始垂直滑动,同一行中的下一个方块会淡入

图片2

看来我在错误的位置设置了过渡和动画,因为即使从红色视图中删除 .transition,它仍然以相同的方式设置动画。无法理解是什么控制它

图3

有人提示如何调整它才能正常工作吗?谢谢!

Chr*_*isR 5

我可以重现你的问题,但我不知道为什么会发生。
但我找到了一个可能的解决方案。如果你将LazyVGrids包裹起来ScrollView,它就会起作用:

struct Item: Identifiable {
    let id = UUID()
}

struct ContentView: View {
    
    @State private var data: [Item] = []
    let column = Array(repeating: GridItem(.flexible()), count: 3)
    
    var body: some View {
        VStack {
            Button("Add") { handleButtonTap() }
            
            ScrollView {
            LazyVGrid(columns: column, alignment: .leading, spacing: 5) {
                ForEach(data) { _ in
                    Color.red
                        .frame(height: 150)
                        .transition(.move(edge: .trailing))
                }
            }
            Spacer()
            }
        }
    }
    
    func handleButtonTap() {
        for index in 0..<9 {
            DispatchQueue.main.asyncAfter(deadline: .now() + Double(1 * index)) {
                withAnimation(.easeInOut(duration: 1)) {
                    let newItem = Item()
                    self.data.append(newItem)
                }
            }
        }
    }
    
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述