简体   繁体   中英

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

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

You can also use something like this

struct NavigationBlock<Destination: View, Content: View>: View {
    @State private var isActive: Bool = false
    var destination: Destination
    var content: (Binding<Bool>) -> Content
    init(destination: Destination, @ViewBuilder content: @escaping (Binding<Bool>) -> Content) {
        self.destination = destination
        self.content = content
    }

    var body: some View {
        Group {
            content($isActive)
            NavigationLink(destination: destination,
                           isActive: $isActive) { Spacer() }.hidden()
        }
    }
}

Usage:

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationBlock(destination: Text("Hello")) { binding in
                Button(action: {
                    print("User did tap 'Hello' button")
                    binding.wrappedValue = true
                }) { Text("Hello button") }
            }
        }
    }
}

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