1

I don't see how this is not a bug. Delete works fine with Text but not TextField. Fails with a Index out of Range exception.

import SwiftUI

struct ContentView: View {
    @State private var messages = ["one", "two"]
    var body: some View {
        NavigationView {
            List {
                ForEach (messages.indices, id: \.self) { index in
   //                 Text($messages[index]) // Works
                    TextField("", text: $messages[index]) // Bug
                }.onDelete(perform: { indexSet in
                    messages.remove(atOffsets: indexSet)
                })
            }
            .navigationTitle(Text("Messages"))
            .navigationBarItems(trailing:
                Button(action: {
                    messages.append("another")
                }, label: {
                    Image(systemName: "plus.circle.fill")
                }))
        }
    }
}

Tried this new code and I can now delete but have an editing issue.

struct ContentView: View {
    @State private var messages = ["one","two"]
    var body: some View {
        NavigationView {
            List {
                ForEach (Array(messages.enumerated()), id: \.element) { index, item in
                    TextField("", text: Binding(
                              get: { self.messages[index] },
                              set: { self.messages[index] = $0 }))
                }.onDelete(perform: { indexSet in
                    messages.remove(atOffsets: indexSet)
                })
            }
            .navigationTitle(Text("Messages"))
            .navigationBarItems(trailing:
                Button(action: {
                    messages.append("another")
                }, label: {
                    Image(systemName: "plus.circle.fill")
                }))
        }
    }
}
  • Does this answer your question https://stackoverflow.com/a/61435489/12299030? – Asperi Dec 18 '20 at 13:54
  • Your id must unique. \.self is not unique. for exmaple when you delete the 2nd element of the array, then the 3rd one becomes 2. – mahan Dec 18 '20 at 14:03
  • @mahan that is true, however, if that were the issue it would fail with just a Text view correct? – Kevin McQuown Dec 18 '20 at 14:08
  • the Binding fix does seem to allow the textfields to be properly deleted, however, I can no longer edit the textfield strings properly – Kevin McQuown Dec 18 '20 at 14:35

0 Answers0