如何在 SwiftUI 中按下时为导航 link 设置动画?

How to animate the navigation link on press in SwiftUI?

我正在尝试通过在按下 NavigationLink() 时提供一些反馈来改善用户体验。 我的意思是一个简单的动画,它先增长然后缩小 link 以表明它被按下或以任何其他方式提供反馈。

这是我要改进的代码:

NavigationLink(
    destination: TrickView(trickId: begginerTricks[index]["trickId"] as! String),
    label: {
        TrickRowView(name: begginerTricks[index]["trickName"] as! String,
        trickType: begginerTricks[index]["trickType"] as! String,
        trickComplete: [false,false,false,false],
        width: width * 0.73, height: height * 0.13)
})
.padding(.bottom, 15)
                                                

这是导航列表 link 中的一个 NavigationLink。

任何有关如何执行此操作的帮助将不胜感激。

有很多方法可以将动画添加到导航中 link。 这是其中之一。 您可以使用 scaleEffectbackground 创建 ButtonStyle 并将其应用于导航 link,或者您也可以根据自己的选择添加其他内容。

按钮样式:

struct ThemeAnimationStyle: ButtonStyle {
    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .font(.title2)
            .foregroundColor(Color.white)
            .frame(height: 50, alignment: .center)
            .background(configuration.isPressed ? Color.green.opacity(0.5) : Color.green)
            .cornerRadius(8)
            .shadow(color: Color.gray, radius: 10, x: 0, y: 0)
            .scaleEffect(configuration.isPressed ? 0.9 : 1.0) //<- change scale value as per need. scaleEffect(configuration.isPressed ? 1.2 : 1.0)
    }
}

使用方法:

var body: some View {
    NavigationView {
        NavigationLink(
            destination: Text("Destination view"),
            label: {
                Text("MyButton")
                    .padding()
            })
            .buttonStyle(ThemeAnimationStyle())
    }
}