Item delete & Move in SwiftUI

100rabhcsmc

Saurabh Chavan

Posted on March 24, 2023

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

💖 💪 🙅 🚩
100rabhcsmc
Saurabh Chavan

Posted on March 24, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Item delete & Move in SwiftUI
100daysofcode Item delete & Move in SwiftUI

March 24, 2023