简体   繁体   中英

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.

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM