Home > Software engineering >  How to have a NavigationLink with swipeActions in a List in SwiftUI
How to have a NavigationLink with swipeActions in a List in SwiftUI

Time:06-06

Consider a List inside of a NavigationView like this:

struct ContentView: View {
    var body: some View {
        NavigationView {
            List {
                Text("Shovel")
                Text("Bucket")
                Text("Sieve")
            
            }.navigationTitle("Sandbox")
        }
    }
}

I want to add .swipeActions to the trailing edge of the list entries like so:

Text("Shovel")
    .swipeActions(edge: .trailing) {
        Button{} label: { Image(systemName: "trash.fill") }
    }

SwipeAction

But once I embed the list entry inside of a NavigationLink, the .swipeActions don't work anymore.

NavigationLink(destination: Text("Shovel")) {
    Text("Shovel")
        .swipeActions(edge: .trailing) {
            Button{} label: { Image(systemName: "trash.fill") }
        }
}

NavigationLink

Now onto the question:

Why is that and how can I have both of these features?

Thanks for your help.

CodePudding user response:

You should add the SwipeAction to the NavigationLink like so:

NavigationLink(destination: Text("Shovel")) {
    Text("Shovel")
}.swipeActions(edge: .trailing) {
    Button{} label: { Image(systemName: "trash.fill") }
}

This behavior happens because the swipe action is a modifier meant for a List Row, when you had only the Text your Text was the row.

However, When Embedding your content in any View (VStack, HStack, NavigationLink...), that Wrapper becomes the Row.

  • Related