top of page
Writer's pictureHui Wang

83. SwiftUI: How to delete elements in a List (NavigationView)

Today I will show you how to delete elements in 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)
                }
                
                /** 9.
                 Add a response to delete method.
                 When an element in the List is removed, run the delete method.
                 */
                .onDelete(perform: delete)
            }
            
            /// 6. Add a navigation button to the upper right corner of the NavigationView.
            .navigationBarItems(trailing: EditButton())
        }
    }
    
    /** 7.
     Add a method that responds to List elements being removed.
     */
    func delete(at offsets: IndexSet) {
        /// 8. 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)
        }
    }
}



 

Follow me on:

Comments


bottom of page