Hubert Rzeminski
Hubert Rzeminski

Reputation: 469

How to animate the navigation link on press in SwiftUI?

I'm trying to improve UX by giving some feedback when the NavigationLink() is pressed. By this I mean a simple animation that grows then shrinks the link to show that it was pressed or any other way to provide feedback.

This is the code I'm trying to improve:

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)
                                                

This is one NavigationLink in a list of navigation links.

Any help on how to do this would be appreciated.

Upvotes: 5

Views: 5926

Answers (1)

Raja Kishan
Raja Kishan

Reputation: 18924

There are many ways to add animation to your navigation link. Here is one of them. You can create ButtonStyle and apply it to the navigation link with the use of scaleEffect, background, or you can also add additional to as per your choice.

ButtonStyle :

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)
    }
}

How to use:

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

enter image description here

Upvotes: 5

Related Questions