DEV Community

Saurabh Chavan
Saurabh Chavan

Posted on

Item delete & Move in SwiftUI

Swip to delete perticular item from the list we can achive using the onDelete() method

Also we can reorder the item using the onMove() metod

import SwiftUI

struct ContentView: View {
    @State private var Names = ["Saurabh","Sachin","Yuraj","Harbhajan","Rohit","Virat","Kapil","Dhoni"]
    var body: some View{
        NavigationView {
            VStack{
                List{
                    ForEach(Names,id: \.self) { name in
                        Text("\(name)")
                    }
                    .onDelete(perform: removeItem)
                    .onMove(perform: moveItem)
                }

            }
            .navigationTitle("Delete & Move")
            .toolbar {
                EditButton()
            }
        }
    }

    func removeItem(at offsets:IndexSet){
        Names.remove(atOffsets: offsets)
    }

    func moveItem(from source:IndexSet,to destination:Int){
        Names.move(fromOffsets: source, toOffset: destination)
    }
}




struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Enter fullscreen mode Exit fullscreen mode

outPut:

Image description

Top comments (0)