article

Tuesday, June 15, 2021

SwiftUI How to delete rows from a list

SwiftUI How to delete rows from a list

SwiftUI makes it easy to let users swipe to delete rows by attaching an onDelete(perform:) handler to some or all of your data.

ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    @State private var users = ["Airi Satou", "Angelica Ramos", "Ashton Cox", "Bradley Greer", "Brenden Wagner", "Brielle Williamson"]

    var body: some View {
        NavigationView {
            List {
                ForEach(users, id: \.self) { user in
                    Text(user)
                }
                .onDelete(perform: delete)
            }
        }
    }

    func delete(at offsets: IndexSet) {
        users.remove(atOffsets: offsets)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
ContentView.swift
 
//
//  ContentView.swift
//  Test
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State private var newTodo = ""
    private let todosKey = "todosKey"
    @State private var allTodos: [TodoItem] = []
    
    var body: some View {
        NavigationView {
          VStack { //vertical stack
               
              HStack { //Horizontal Stack
              TextField("Add todo...", text: $newTodo)
                .textFieldStyle(RoundedBorderTextFieldStyle())
               
              Button(action: {
                guard !self.newTodo.isEmpty else { return }
                self.allTodos.append(TodoItem(todo: self.newTodo))
                self.newTodo = ""
                self.saveTodos()
              }) {
                  Image(systemName: "plus")
              }
              .padding(.leading, 5)
            }.padding() //end horizontal stack
   
            List { //List view to display all of the to-dos in our allTodos
              ForEach(allTodos) { todoItem in
                Text(todoItem.todo)
              }.onDelete(perform: deleteTodo)
            }.onAppear(perform: loadTodos)
            
          }//end vertical stack
          .navigationBarTitle("Todos")
        }
   }
    
    //Storing To-dos in UserDefaults
    //UserDefaults is a database where you store key-value
    //https://developer.apple.com/documentation/foundation/userdefaults
    
    private func saveTodos() {
      UserDefaults.standard.set(try? PropertyListEncoder().encode(self.allTodos), forKey: todosKey)
    }
    
    private func loadTodos() {
      if let todosData = UserDefaults.standard.value(forKey: todosKey) as? Data {
        if let todosList = try? PropertyListDecoder().decode(Array<TodoItem>.self, from: todosData) {
          self.allTodos = todosList
        }
      }
    }
    
    private func deleteTodo(at offsets: IndexSet) {
      self.allTodos.remove(atOffsets: offsets)
      saveTodos()
    }
    
}

//Add codable to make Sure each item encoded and decoded
struct TodoItem: Codable, Identifiable { //Identifiable protocol this ensures that the system can distinguish one TodoItem from another
    var id = UUID()
  let todo: String
}

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

Related Post