top of page
Writer's pictureHui Wang

85. SwiftUI: How to delete and move elements of a List (NavigationView)

Today I will show you how to delete and move elements of a List. (demo with NavigationView).


import SwiftUI

struct ContentView: View {
    
    /// 1. Use an array as the data source for the List.
    @State var colors = ["Red", "Green", "Blue"]
    
    var body: some View {
        
        /// 2. Add a NavigationView. The function of NavigationView is similar to that of UINavigationController, which is mostly used to switch between views.
        NavigationView {
            
            /// 3. create a List
            List {
                
                /// 4. Add a forEach method to iterate over the array.
                ForEach(colors, id: \.self) { color in
                    
                    /// 5. Use Text to show the elements.
                    Text(color)
                }
                
                /// 12. Respond to `delete` and `move` events.
                .onDelete(perform: delete)
                .onMove(perform: move)
            }
            
            /// 6. Set the title text of the navigation bar
            .navigationTitle(Text("Edit"))
            .navigationBarTitleDisplayMode(.large)
            
            /// 7. add an edit button
            .toolbar { EditButton() }
        }
    }
    
    /** 8.
     Add a method that responds to List elements being removed.
     */
    func delete(at offsets: IndexSet) {
        /// 9. Get the first element of IndexSet, and then delete the array element corresponding to the index.
        if let first = offsets.first {
            colors.remove(at: first)
        }
    }
    
    /** 10.
     Add a method that responds to List elements being moved.
     This method has two parameters:
     - source: The original position's index.
     - destination: The destination position's index.
     */
    func move(from source: IndexSet, to destination: Int) {
        /// 11. When the elements in the List are moved, the elements in the array also need to be moved to keep the interface and data from changing simultaneously.
        self.colors.move(fromOffsets: source, toOffset: destination)
    }
}



 

Follow me on:

Comments


bottom of page