我正在制作一款带有动画的SwiftUI应用程序.一个很适合制作动画的地方是卡片上图像的位置,因为卡片会转换状态,图像变得交互.
The issue is that this image becomes a Menu
, which introduces a strange animation effect. This is what it looks like in a sample project:
值得注意的是,在取消 Select 时,它会正确地设置动画--图像会翻转,而不是从底部显示.
I know that the issue is with the Menu
because if I pull the menu label out, the animation works fine:
以下是演示该问题的简单示例代码:
import SwiftUI
struct ContentView: View {
@State var selected = false
@Namespace var animation
var body: some View {
VStack {
Text(selected ? "Selected card" : "Deselected card").font(.title).padding(20)
if selected {
HStack {
Button(action: {}, label: {
Image(systemName: "trash")
})
Spacer()
Menu(content: {
Button("Order Now", action: {})
Button("Adjust Order", action: {})
}, label: {
Image(systemName: "paperplane")
.matchedGeometryEffect(id: "send", in: animation)
})
}
.padding(20)
} else {
HStack {
Text("Timestamp")
Spacer()
Image(systemName: "paperplane")
.matchedGeometryEffect(id: "send", in: animation)
}
}
}
.foregroundColor(.white)
.padding(20)
.background(.blue)
.clipShape(RoundedRectangle(cornerRadius: 24))
.onTapGesture {
withAnimation {
selected.toggle()
}
}
.padding(20)
}
}
要"修复"它,只需将Image
移出菜单标签,并查看它的动画是否正确.
我try 了几种解决方法来解决此问题:
- 使"取消 Select "的手臂使用
Menu
和.disabled
,然后将matchedGeometryEffect
移动到菜单本身.这是works,但不是我想要的,因为在我的实际用例中,菜单是图像和文本标签的HStack
和text labels do not behave nicely withmatchedGeometryEffect
- 使用
.overlay
和/或ZStack
隐藏图像下方的菜单.这也可以正常工作,但这意味着当点击菜单图像时,图像不会像正常情况下那样灰显. - 我已经考虑过让图像只是一个按钮,并在不使用
Menu
的情况下创建菜单.这看起来很恶心.
任何关于如何最好地实现这一点的 idea 都将不胜感激!