3

I am trying to create a list that only allows users to delete after entering an editing mode. I attempted to try using ternary operation in the onDelete modifier but was unable to figure it out. Any recommendations?

Here is my code:

struct ContentView: View {
    @State private var stuff = ["First", "Second", "Third"]
    @State private var check = false
    
    var body: some View {
        Form {
            Button(action: { check.toggle() }, label: { Text(check ? "Editing" : "Edit") })
            
            ForEach(0..<stuff.count) { items in
                Section{ Text(stuff[items]) }
            }
             .onDelete(perform: self.deleteItem)
               
        }
    }
    
    private func deleteItem(at indexSet: IndexSet) {
        self.stuff.remove(atOffsets: indexSet)
    }
}

3 Answers 3

5

I assume you look for the following

var body: some View {
    Form {
        Button(action: { check.toggle() }, label: { Text(check ? "Editing" : "Edit") })
        
        ForEach(0..<stuff.count) { items in
            Section{ Text(stuff[items]) }
        }
         .onDelete(perform: self.deleteItem)
         .deleteDisabled(!check)             // << this one !!
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

But don't you want a function of item? This is outside the scope of item.
I tried some code inside the ForEach and it still works there.
@MarkAurelius, it is possible to do this by-row, it is possible to do this for all, there is no conflict here - it depends on app needs. See this stackoverflow.com/a/65246568/12299030.
worked. life savior
0

This can be done directly within the .onDelete method, using the ternary operator:

.onDelete(perform: check ? deleteItem : nil)

Comments

-1
struct ContentView: View {
    @State private
    var stuff = ["First", "Second", "Third"]
    var body: some View {
        NavigationView {
            Form {
                ForEach(0..<stuff.count) { item in
                    Section {
                        Text(stuff[item])
                    }
                }
                .onDelete(
                    perform: delete)
            }
            .navigationBarItems(
                trailing:
                    EditButton()
            )
            .navigationTitle("Test")
        }
    }
}

extension ContentView {
    private func delete(at indexSet: IndexSet) {
        stuff.remove(atOffsets: indexSet)
    }
}

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.