Swiftui Table Custom Swipe

How to have a NavigationLink with swipeActions in a List in SwiftUI

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 Text, it was the row.

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

SwiftUI swipeActions reload results in leading blank space and broken swipe

I am still not sure why your implementation is causing this behavior, other than that you are completely switching between two separate views(Zstack vs. ProgressView). My suspicion is that the change back and forth is simply putting the List into some weird state. The fix, however, is simple; put the conditional inside of the ZStack:

struct ContentView: View {
@ObservedObject var viewModel: ViewModel

var body: some View {
ZStack {
// Move the conitional inside of the ZStack.
// Always use .isEmpty for this sort of test. Faster and
// less resources than count
if !viewModel.items.isEmpty {
List {
// I made Item an Identifiable struct. Deleting items
// identified as .self can lead to issues in a ForEach
ForEach(viewModel.items) { item in
Text(item.name)
.swipeActions {
Button {
viewModel.removeAction(item: item)
} label: {
Text("Remove")
}
.tint(.orange)
}
}
}
} else {
Text("Progress View")
}
}
}
}

extension ContentView {
class ViewModel: ObservableObject {
@Published var items: [Item]

init(items: [Item]) {
self.items = items
}

func removeAction(item: Item) {
if let index = items.firstIndex(where: { $0 == item }) {
items.remove(at: index)
}

let itemsSaved = items
items = []

DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.items = itemsSaved
}
}
}
}

// I made this as a data model.
struct Item: Identifiable, Hashable {
var id = UUID()
var name: String
}


Related Topics



Leave a reply



Submit