TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Remove Items from list

Forums > SwiftUI

Say I have this setup:

struct DeleteFromList: View {
    var body: some View {
        LazyVStack {
            ForEach(0..<10) { i in
                DeleteRowView(i: i)
            }
        }
    }
}

struct DeleteRowView: View {
    var i: Int

    var body: some View {
        Button {
            // Remove this row from the list
        } label: {
            Text("Delete me at \(i)!")
        }
    }
}

and I want the buttons to work.

The solution I had was:

struct DeleteFromList: View {
    @State private var list = [Int](0..<10)

    var body: some View {
        LazyVStack {
            ForEach(list, id: \.self) { i in
                DeleteRowView(i: i) {
                    list.remove(at: i)
                }
            }
        }
    }
}

struct DeleteRowView: View {
    var i: Int
    var remove: () -> Void

    var body: some View {
        Button {
            remove()
        } label: {
            Text("Delete me at \(i)!")
        }
    }
}

but this crashes the app.

2      

SwiftUI has a built in funtion for swipe to delete

struct ContentView: View {
    @State private var list = Array(0..<10)

    var body: some View {
        List {
            ForEach(list, id: \.self) { i in
                Text("Row \(i)")
            }
            .onDelete(perform: delete)
        }
    }

    func delete(_ offsets: IndexSet) {
        list.remove(atOffsets: offsets)
    }
}

2      

I am implementing my own swipe actions, so unless there is a way to disable the swipe that comes with onDelete that won't do.

2      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.