How to perform an action after NavigationLink is tapped?

后端 未结 4 922
梦毁少年i
梦毁少年i 2020-12-10 14:29

I have a Plus button in my first view. Looks like a FAB button. I want to hide it after I tap some step wrapped in NavigationLink. So far I have something like this:

4条回答
  •  攒了一身酷
    2020-12-10 14:50

    I'm using the following code. I prefer it to just NavigationLink by itself because it lets me reuse my existing ButtonStyles.

    
    struct NavigationButton: View {
        var action: () -> Void = { }
        var destination: () -> Destination
        var label: () -> Label
    
        @State private var isActive: Bool = false
    
        var body: some View {
            Button(action: {
                self.action()
                self.isActive.toggle()
            }) {
                self.label()
                  .background(
                    ScrollView { // Fixes a bug where the navigation bar may become hidden on the pushed view
                        NavigationLink(destination: LazyDestination { self.destination() },
                                                     isActive: self.$isActive) { EmptyView() }
                    }
                  )
            }
        }
    }
    
    // This view lets us avoid instantiating our Destination before it has been pushed.
    struct LazyDestination: View {
        var destination: () -> Destination
        var body: some View {
            self.destination()
        }
    }
    
    

    And to use it:

    var body: some View {
      NavigationButton(
        action: { print("tapped!") },
        destination: { Text("Pushed View") },
        label: { Text("Tap me") }
      )
    }
    

提交回复
热议问题