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

Hub*_*ski 5 animation user-experience ios swiftui swiftui-navigationlink

我试图通过在按下 NavigationLink() 时提供一些反馈来改进用户体验。我的意思是一个简单的动画,它会增长然后缩小链接以显示它被按下或以任何其他方式提供反馈。

这是我正在尝试改进的代码:

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)
                                                
Run Code Online (Sandbox Code Playgroud)

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

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

Raj*_*han 5

有多种方法可以向导航链接添加动画。这是其中之一。您可以ButtonStyle使用 、 来创建并将其应用到导航链接scaleEffectbackground或者您也可以根据您的选择添加其他内容。

按钮样式:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

如何使用:

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

在此输入图像描述