【问题标题】:SwiftUI: Index out of range when last element gets removedSwiftUI:删除最后一个元素时索引超出范围
【发布时间】:2021-11-12 07:44:45
【问题描述】:

我有一个用 LazyVStack 制作的清单,我为清单项目实现了删除功能,但由于某种原因,只有当我尝试删除最后一个元素时,app 才会因“索引超出范围”而崩溃

这是我的代码:

struct ChecklistView: View {
    // Properties
    // ==========
    @ObservedObject var checklist = Checklist()
    @ObservedObject var viewModel: ChecklistViewModel
    @Binding var checklistItems: [ChecklistItem]
    @State var newItemName = ""
    @State var newChecklistItemViewIsVisible = false
    @State var presentAddNewItem = true
    let offlineMode: Bool

    var body: some View {
        VStack {
            LazyVStack {
                ForEach(checklistItems) { item in
                    HStack {
                        RowView(checklistItem: $checklistItems[item], viewModel: viewModel)
                            .listRowInsets(.init(top: 0, leading: 8, bottom: 0, trailing: 0))
                            .padding(.horizontal, 12)
                            .padding(.top, 12)
                            .padding(.bottom, 4)

                        Button {
                            //Prints the correct index number for the last element in the array, but when I remove the last element, always crashes.
                            print(index)
                            if let index = checklistItems.firstIndex(where: {$0.id == checklistItems[item].id}){
                                checklistItems.remove(at: index)
                            }
                        } label: {
                            Text("X")
                        }
                    }

                    Divider()
                        .frame(width: 311)
                }
            }
        }
        .frame(width: UIScreen.main.bounds.width - 32)
        .background(backgroundSecondary)
        .cornerRadius(16)
        .overlay(
            RoundedRectangle(cornerRadius: 16)
                .stroke(borderGray, lineWidth: 1)
        )
    }
}

【问题讨论】:

  • 鉴于您的ForEach(checklistItems),item 不应该是 ChecklistItem 类型吗?但是你用它来下标,就好像它是 Int 类型一样。这是你的实际代码?

标签: arrays swiftui lazyvstack


【解决方案1】:

ForEach(checklistItems) { item in 中的 item 不是数组的索引 checklistItems,它是一个ChecklistItem。但是,您将其用作索引 RowView(checklistItem: $checklistItems[item], ...。这是不正确的。

使用indices 尝试这种方法来解决您的问题:

ForEach(checklistItems.indices, id: \.self) { ndx in
    HStack {
        RowView(checklistItem: $checklistItems[ndx], viewModel: viewModel)
            .listRowInsets(.init(top: 0, leading: 8, bottom: 0, trailing: 0))
            .padding(.horizontal, 12)
            .padding(.top, 12)
            .padding(.bottom, 4)

        Button {
            print(ndx)
            checklistItems.remove(at: ndx)
        } label: {
            Text("X")
        }
    }
    Divider().frame(width: 311)
}

你也可以这样用:

ForEach(Array(zip(checklistItems.indices, checklistItems)), id: \.0) { ndx, item in

【讨论】:

  • 在这种情况下,您很可能不想通过索引id。当您从 checklistItems 添加/删除项目时,您正在使已经存在的视图更改 id。这会破坏动画,因为视图 ​​ID 不是恒定的。相反,您应该将ChecklistItem 与Identifiable 一致,然后在您的第二段代码中使用id: \.1.id 标识。
  • 看起来这两种解决方案在最后一个项目删除时仍然会使我的应用程序崩溃
  • 乔治的好建议。它可能“看起来”会崩溃,但在我的测试中没有。可以肯定的是,向我们展示 ChecklistItem 中的内容
【解决方案2】:

我找到了解决方案,我将 forEach 更改为:

ForEach(checklistItems.indices, id: \.self) { index in
                    HStack {
                        RowView(
                            checklistItem:
                                Binding(
                                    get: { self.checklistItems[index] },
                                    set: { self.checklistItems[index] = $0 }
                                ),
                            viewModel: viewModel
                        )
                        .padding(.leading, 12)

                        if checklistEditMode {
                            Button {
                                checklistItems.remove(at: index)
                            } label: {
                                Image("XCircle")
                                    .resizable()
                                    .frame(width: 18, height: 18)
                            }
                            .padding(.trailing, 12)
                        }
                    }
                    .padding(.horizontal, 12)
                    .padding(.top, 12)
                    .padding(.bottom, 4)

                    Divider()
                        .frame(width: 311)
                }

它现在可以正常工作,没有崩溃,感谢this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多