6

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 Answer 1

8

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)
        })
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.