【发布时间】:2021-03-19 17:03:45
【问题描述】:
我有一个使用视图模型填充的简单列表:
@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
})
}
视图模型在哪里:
class StepDataViewModel: ObservableObject {
@Published var steps: [StepData] = []
func removeStep(index: IndexSet) {
steps.remove(atOffsets: index)
}
}
StepData 就是这个:
struct StepData: Equatable, Hashable {
var theIndex: Int
var theValue: Double
}
滑块:
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)
}
}
}
}
现在,.onDelete 显然已附加到列表中,因此当按删除时我收到了正确的行 index。
应用程序因索引越界而崩溃的原因是什么?传递给我索引的列表是否?
我收到此错误:
致命错误:索引超出范围:文件 Swift/ContiguousArrayBuffer.swift,第 444 行
可能是由“TheSlider”中的直接数组引用引起的?如果是,我如何使用theValue 将其更改为Binding 可更新?
【问题讨论】:
-
为什么需要Hashable和Identifiable?如果你要使用\.self,那么你只需要Hashable。
-
这是崩溃的原因吗?
-
一开始我需要尽可能多地清理代码,所以我问。
-
我从问题中删除了
Identifiable,当然崩溃也是一样的。 -
让我控制吧,这不难
标签: swift list foreach swiftui binding