iosswiftuinavigationlink

SwiftUI - Trigger other actions when click NavigationLink


I create a list view with a button in an up layer. I want to hide the button immediately right after user clicks the NavigationLink and doesn't see it in a detail view.

I implement it successfully by using @State var showAddButton and control it by onDisappear and onAppear action like below, but the button won't disappear if the main view doesn't disappear completely.

Does anyone have any other solution to trigger other actions and keep the original link action of NavigationLink?

@State var showAddButton = true

    var body: some View {

        ZStack{

            NavigationView{
                List{
                    ForEach(items, id: \.id){ item in
                        NavigationLink(destination: WorkItemDetailView(item: item)){
                            WorkItemListRow(item: item)
                        }.onDisappear{self.showAddButton = false}
                            .onAppear{self.showAddButton = true}

                    }
                }
                .navigationBarTitle("List", displayMode: .inline)   
            }           

            if showAddButton {
                FloatAddButton()
            }
        }
    }

Solution

  • If you want to stick that button to the main view, you may switch the position of ZStack:

       NavigationView{
            ZStack{
            List{
                ForEach(items, id: \.self){ item in
                    NavigationLink(destination: WorkItemDetailView(item: item)){
                        WorkItemListRow(item: item)
                    }
    
                }
    
            }
            .navigationBarTitle("List", displayMode: .inline)
            Button("mybutton",action: {})}
        }