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)
}
}
我有一个按钮,用于启动动画效果:
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)
}
}
}
}
动画应使用幻灯片效果以 1 秒的间隔将新的红色方块一一添加到网格中,但有 2 个问题:
- 即使我为红色视图设置了特定的过渡,该过渡也会被忽略,并且会添加带有淡入淡出效果的方块
- 每次将行中的第一个方块添加到网格上的新行中,它从行的中间出现,并开始垂直滑动,同一行中的下一个方块在
中淡入淡出<图片src="https://i.sstatic.net/AW7Tg.png" alt="image2">
看来我在错误的位置设置了过渡和动画,因为即使从中删除 .transition红色视图,它仍然以相同的方式进行动画处理。无法理解是什么控制它
有人知道如何调整它以使其正常工作吗? 谢谢!
I have a LazyVGrid that is defined like this:
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)
}
}
I have a button, that starts an animation effect:
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)
}
}
}
}
The animation should add the new Red squares into the grid one by one with 1 second intervals using a slide effect, but there are 2 issues:
- even though I set a specific transition for the Red color view, the transition is ignored and the squares are added with a fade in effect
- each time the first square in the row, is added in a new row on the grid, it appears from the middle of the row, and starts to slide vertically, the next squares in same row fade in
It appears I'm setting the transition and animation in the wrong place, because even if remove the .transition from the Red view, it still animates it the same way. Can't understand what controls it
Anyone has a hint how to adjust it to work properly?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我可以重现您的问题,但我不知道为什么会发生。
但我找到了一个可能的解决方案。如果将
LazyVGrid
包装在ScrollView
中,它就可以工作:I can reproduce your issue, and I don't know why it happens.
But I found a possible solution. If you wrap the
LazyVGrid
in sScrollView
it works: