Is there a way to change images while using a image inside a NavigationLink in SwiftUI?

34 Views Asked by At

I'm relatively new to Swift development and I'm encountering an issue with SwiftUI that I haven't been able to solve despite days of research.

I am trying to create a view where an image acts as a button within a NavigationLink. The desired behavior is as follows: when the user taps on the image, the image should briefly change to a different, "highlighted" version of the image before the navigation action takes place and the user is taken to a new page.

I attempted to implement this behavior using a Button instead, hoping to achieve the image change upon tap. This has worked. However, I encountered issues with combining button actions with NavigationLink behavior.

struct HomeView: View {
    @State private var analysisClicked = false
    @State private var dataClicked = false
    var body: some View {
        NavigationStack {
            VStack {
                Image("logo-icon")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(height: 50)
                    .padding(.top, 50)
                Spacer()
                Button(action: {
                    self.analysisClicked.toggle()}){
                        Image(analysisClicked ? "start-analysis-active":"start-analysis-inactive")
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(height: 85)
                            .padding(.bottom, 10)
                    }
                NavigationLink {
                    DataView()
                } label: {
                    Image(analysisClicked ? "view-data-active":"view-data-inactive")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(height: 85)
                        .padding(.bottom, 10)
                }
                Spacer()
                
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.white)
        }
    }
}
0

There are 0 best solutions below