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
Swift Memory Management: Storing Func in Var
Updating a @Published Variable Based on Changes in an Observed Variable
iOS 13, Custom Image, Title and Subtitle in the Presented Uiactivityviewcontroller
How to Check If Core Data Is Empty
Avplayer Can't Resume After Paused + Some Waiting
Instagram Explorer Searchbar and Tableview
Unsafemutablepointer<Void> to Concrete Object Type
Accessibility (Voice Over) with Sprite Kit
Using Animoji/Memoji as Profile Photo
Combined Chart (Line- and Bar Chart) Using iOS-Charts
How to Duplicate a Sprite in Sprite Kit and Have Them Behave Differently
Float Is Not Convertible to 'Mirrordisposition' Swift What Is Mirrordisposition
Converting Audiobuffer to Cmsamplebuffer with Accurate Cmtime
How to Make Player Move to Opposite Side While Is in a Path
How to Access App Specific Folder and Use It to Backup or Some App Specific Data? in Swift