简体   繁体   English

SwiftUI List.onDelete:索引超出范围

[英]SwiftUI List .onDelete: Index out of range

I have a simple list populated using a view-model:我有一个使用视图模型填充的简单列表:

@ObservedObject var sdvm = StepDataViewModel()

[...]

List {
    ForEach (vm.steps.indices, id: \.self) { idx in
        TheSlider(value: self.$vm.steps[idx].theValue, index: self.vm.steps[idx].theIndex)
    }
    .onDelete(perform: { indexSet in
        self.vm.removeStep(index: indexSet) // <--- here
    })
}

Where the viewmodel is this:视图模型在哪里:

class StepDataViewModel: ObservableObject {
    @Published var steps: [StepData] = []

    func removeStep(index: IndexSet) {
        steps.remove(atOffsets: index)
    }    
}

and the StepData is this one: StepData就是这个:

struct StepData: Equatable, Hashable {
    var theIndex: Int
    var theValue: Double
}

TheSlider :滑块

struct TheSlider: View {
    @Binding var value: Double
    @State   var index: Int

    var body: some View {
        ZStack {
            Slider(value: $value, in: 0...180, step: 1)
                .padding()
            HStack {
                Text("[\(index)]")
                    .font(.body)
                    .fontWeight(.black)
                    .offset(y: -20.0)

                Text("\(Int(value))")
                    .offset(y: -20.0)
            }
        }
    }
}

Now, .onDelete is obviously attached to the List, so I receive the correct row index when press delete.现在, .onDelete显然已附加到列表,因此当按删除时我收到正确的行index
For what reason the app crash for index-out-of-bound?应用程序因索引越界而崩溃的原因是什么? Is the list that pass me the index, or not?传递给我索引的列表是否?

I receive this error:我收到此错误:

Fatal error: Index out of range: file Swift/ContiguousArrayBuffer.swift, line 444致命错误:索引超出范围:文件 Swift/ContiguousArrayBuffer.swift,第 444 行

Can be caused by the direct array reference in the " TheSlider "?可能是由“ TheSlider ”中的直接数组引用引起的? If yes, how I can change it using theValue as Binding updatable?如果是,我如何使用theValue作为可更新的Binding来更改它?

This is a SwiftUI bug reported in Deleting list elements from SwiftUI's List .这是从 SwiftUI 的 List 中删除列表元素中报告的 SwiftUI 错误。

The solution is to use the extension from here that prevents accessing invalid bindings:解决方案是使用此处的扩展来防止访问无效绑定:

struct Safe<T: RandomAccessCollection & MutableCollection, C: View>: View {
   
   typealias BoundElement = Binding<T.Element>
   private let binding: BoundElement
   private let content: (BoundElement) -> C

   init(_ binding: Binding<T>, index: T.Index, @ViewBuilder content: @escaping (BoundElement) -> C) {
      self.content = content
      self.binding = .init(get: { binding.wrappedValue[index] }, 
                           set: { binding.wrappedValue[index] = $0 })
   }
   
   var body: some View { 
      content(binding)
   }
}
List {
    ForEach(vm.steps.indices, id: \.self) { index in
        Safe(self.$vm.steps, index: index) { binding in
            TheSlider(value: binding.theValue, index: vm.steps[index].theIndex)
        }
    }
    .onDelete(perform: { indexSet in
        self.vm.removeStep(index: indexSet)
    })
}

I believe this is the same problem addressed here which is a loss of consistency between the indices in the ForEach loop and what is deleted.我相信这与此处解决的问题相同,即 ForEach 循环中的索引与删除的索引之间的一致性丢失。 Add a separate array for the indices and use it for iteration and deletion like this:为索引添加一个单独的数组并将其用于迭代和删除,如下所示:

    @ObservedObject var vm = StepDataViewModel()
    @State var indices: [Int] = Array(0..<3)
    
    var body: some View {
        
        List {
            ForEach (indices, id: \.self) { idx in
                TheSlider(value: self.$vm.steps[idx].theValue, index: self.vm.steps[idx].theIndex)
            }
            .onDelete(perform: { indexSet in
                indices.remove(atOffsets: indexSet) // <--- here
            })
        }

You will need some additional code to handle deletion of the corresponding items in the model您将需要一些额外的代码来处理 model 中相应项目的删除

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM