Como lidar .aoexcluir para SwiftUI lista de matriz com .invertida()

0

Pergunta

Eu estou tentando fazer um básico SwiftUI lista na qual cada novo item de lista é apresentado no topo da lista. Para fazer isso, eu acrescentado .invertida() para a matriz passado para o loop ForEach, representado por viewModel.itemList. Eu também .aoexcluir para lidar com a remoção da lista de itens. No entanto, quando eu excluir um item, tal como o último item na lista, em vez disso, elimina o último item na matriz (o item no topo da lista). Como posso configurar .aoexcluir para excluir o item correto quando a matriz é revertido?

Veja o meu código abaixo. Obrigado!

Exibiçãode conteúdo

struct ContentView: View {
    
    @StateObject var viewModel = ToDoListViewModel()
    @State private var listItemName = ""
        
    var body: some View {
        NavigationView {
            VStack(alignment: .leading) {
                List {
                    ForEach(viewModel.itemList.reversed()) { item in
                        Text(item.listItem)
                    }.onDelete { index in
                        self.viewModel.itemList.remove(atOffsets: index)
                    }
                }
                
                HStack {
                    TextField("Enter List Item", text: $listItemName)

                    Button(action: {
                        viewModel.addToList(ToDoModel(listItem: listItemName))
                        listItemName = ""
                    }) {
                        Image(systemName: "plus")
                            .font(.largeTitle)
                            .frame(width: 75, height: 75)
                            .foregroundColor(Color.white)
                            .background(Color.blue)
                            .clipShape(Circle())
                    }
                }.frame(minWidth: 100, idealWidth: 150, maxWidth: 500, minHeight: 30, idealHeight: 40, maxHeight: 50, alignment: .leading)
                    .padding(.leading, 16)
                    .padding(.trailing, 16)
            }.navigationBarTitle("To Do List", displayMode: .inline)
        }
    }
}

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

Modelo

struct ToDoModel: Identifiable, Codable {
    var id = UUID()
    var listItem: String = ""
}

ViewModel

class ToDoListViewModel: ObservableObject {
    @Published var itemList = [ToDoModel]()

    func addToList( _ item: ToDoModel) {
        itemList.append(item)
    }
}
arrays swift swiftui swiftui-list
2021-11-21 23:25:33
2

Melhor resposta

1

você também pode tentar essa abordagem:

.onDelete { index in
    // get the item from the reversed list
    let theItem = viewModel.itemList.reversed()[index.first!]
    // get the index of the item from the viewModel, and remove it
    if let ndx = viewModel.itemList.firstIndex(of: theItem) {
        viewModel.itemList.remove(at: ndx)
    }
}
2021-11-22 00:15:13
1

Ressalva: isso não pode ser mais , através de algoritmos eficientes. No entanto, a simples exclusão de um List, ele deve executar bem.

.onDelete { offsets in
    let reversed = Array(viewModel.itemList.reversed()) //get the reversed array -- use Array() so we don't get a ReversedCollection
    let items = Set(offsets.map { reversed[$0].id }) //get the IDs to delete
    viewModel.itemList.removeAll { items.contains($0.id) } //remove the items with IDs that match the Set
}
2021-11-22 00:11:34

Em outros idiomas

Esta página está em outros idiomas

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................