Search code examples
iosswiftuiswiftui-navigationlink

iOS SwiftUI - use NavigationLink and perform additional action


            NavigationLink(destination: ShowWebView(showWhat: "privacy"), label: {
                HStack(spacing: 32) {
                    
                    Image(systemName: "info.square")
                        .font(.title2)
                        .frame(width: 26)
                    
                    Text("privacy_policy")
                    
                }
                .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
            })

I need to perform additional action when opening ShowWebView.

This is what I've tried:

            NavigationLink(destination: ShowWebView(showWhat: "privacy"), label: {
                HStack(spacing: 32) {
                    
                    Image(systemName: "info.square")
                        .font(.title2)
                        .frame(width: 26)
                    
                    Text("privacy_policy")
                    
                }
                .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                .onTapGesture {
                    withAnimation(){
                        self.offsetMenu = UIScreen.main.bounds.height
                    }
                }
            })

but this way only what's inside onTapGesture is performed but the view ShowWebView doesn't get opened.


Solution

  • You can change the variable applying the .onAppear modifier to ShowWebView.

    This is the code to obtain what you are looking for:

    NavigationLink {
        ShowWebView(showWhat: "privacy")
    
            // Add this modifier
            .onAppear {
                withAnimation {
                    self.offsetMenu = UIScreen.main.bounds.height
                }
            }
        
    } label: {
        HStack(spacing: 32) {
            
            Image(systemName: "info.square")
                .font(.title2)
                .frame(width: 26)
            
            Text("privacy_policy")
            
        }
        .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
    }