尝试删除行时具有绑定视图的ForEach崩溃

时间:2020-10-02 21:22:05

标签: swift swiftui

我有以下代码,尝试删除该行时崩溃。

Fatal error: Index out of range: file Swift/ContiguousArrayBuffer.swift, line 444
2020-10-02 17:08:37.983723-0400 HapticFactory[4201:213536] Fatal error: Index out of range: file Swift/ContiguousArrayBuffer.swift, line 444

该如何解决?还是我必须以其他方式解决这个问题?

代码:

import SwiftUI

struct Tag: Identifiable {
    var id = UUID()
    var value: String = "ColorBlue"
    var color: Color = .blue
}

class ItemsViewModel: ObservableObject {
    @Published var tags: [Tag] = []
    
    func addTag(tag: Tag) {
        tags.append(tag)
    }
}

struct ContentView: View {
    @ObservedObject var viewModel = ItemsViewModel()
    
    var body: some View {
        List {
            ForEach(self.viewModel.tags.indices, id: \.self) { index in
                ColorPicker(selection: self.$viewModel.tags[index].color) {
                    TextField("", text: self.$viewModel.tags[index].value)
                }
            }.onDelete(perform: self.deleteRow)
            Button(action: { self.viewModel.addTag(tag: Tag()) }, label: {
                Text("Add Tag")
            })
        }
    }
    
    private func deleteRow(at indexSet: IndexSet) {
        self.viewModel.tags.remove(atOffsets: indexSet)
    }
}

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

0 个答案:

没有答案