top of page
Writer's pictureHui Wang

78. SwiftUI: How to insert new items to a List (NavigationView)

Today I will show you how to insert new items into 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 to show how to add new items.
            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)
                }
                /// 6. Add an onInsert method to insert new items to the array.
                .onInsert(of: ["public.text"], perform: onInsert)
            }
            
            /// 8. Set NavigationView's title.
            .navigationTitle("Insert new items")
            .navigationBarTitleDisplayMode(.large)
            
            /// 9. Add a navigation button to the upper right corner of the NavigationView.
            .navigationBarItems(
                trailing:
                    /// 10. When you click on the Button, the addItem method will be called.
                Button(action: addItem, label: {
                    Text("Add")
                })
            )
        }
    }
    
    /** 7.
     Add onInsert method.
     Call this method when elements are inserted into the original view.
     */
    func onInsert(at index: Int, _ items: [NSItemProvider]) {
        for item in items {
            _ = item.loadObject(ofClass: String.self) { droppedString, _ in
                if let text = droppedString {
                    DispatchQueue.main.async {
                        colors.insert(text, at: index)
                    }
                }
            }
        }
    }
    
    /** 11.
     Add addItem method.
     It is used to respond when the navigation button is clicked.
     When the navigation button is clicked, a new string is added to the end of the array.
     */
    func addItem() {
        colors.append("White")
    }
}

#if DEBUG
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif



 

Follow me on:

Comentários


bottom of page