1
votes

Below is basic code for a SwiftUI list that allows swipe-to-delete functionality on all rows. Is it possible to limit this to specific rows/indexes? (ie. only allow the swipe-to-delete behavior on the 3rd row, but disable it on all other rows?)

In my app, I have a List of Comments and I want a user to be able to swipe-to-delete their own comment, but the swipe-to-delete behavior should be disabled on all other comments. I know this is possible in UIKit with one of the UITableView delegates but I'm not sure how to implement it in SwiftUI.

struct ListTest: View {
    var body: some View {
        List {
            ForEach(0..<50) { index in
                Text("index is \(index)")
            }
            .onDelete(perform: { indexSet in
                print(indexSet)
            })
        }
    }
}
1

1 Answers

0
votes

Here is a solution. Tested with Xcode 12.1 / iOS 14.1

    List {
        ForEach(0..<50) { index in
             Text("index is \(index)")
                .deleteDisabled(index == 3)       // << ex. !!
        }
        .onDelete(perform: { indexSet in
            print(indexSet)
        })
    }