[英]Crashing remove items in list with modal view in SwiftUI
when try to remove item in list from modal view, gets crash Thread 1: Fatal error: Index out of range
当尝试从模式视图中删除列表中的项目时,会崩溃
Thread 1: Fatal error: Index out of range
for example,例如,
if comment out textfield part, there is no crash.如果注释掉文本字段部分,则不会崩溃。 not really sure what's going on...
不太清楚发生了什么……
struct ContentView: View {
@State var strs = ["1", "2", "3"]
@State var showingDetail: Bool = false
var body: some View {
List {
ForEach(Array(strs.enumerated()), id: \.element) { index, str in
VStack {
Button(action: {
self.showingDetail.toggle()
}) {
Text("show modal")
.sheet(isPresented: self.$showingDetail) {
ModalView(showingDetail: self.$showingDetail, strs:self.$strs,
index: index)
}
TextField("", text:self.$strs[index])
}
}
}
}
}
}
struct ModalView: View {
@Binding var showingDetail: Bool
@Binding var strs: [String]
var index: Int = 0
var body: some View {
Button(action: {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.strs.remove(at: self.index)
}
self.showingDetail.toggle()
}) {
Text("delete")
}
}
}
When you delete the element in an array the number of elements in the array reduces.当您删除数组中的元素时,数组中的元素数量会减少。 So, when you delete the first element ie., index 0 then there are only 2 more left.
所以,当你删除第一个元素,即索引 0 时,只剩下 2 个了。 Now you could delete the element at index 1 which is the last element, and the array is left with only 1 element at index 0. So when you try to access the third element at index 2 you get a crash.
现在您可以删除索引 1 处的元素,即最后一个元素,并且数组在索引 0 处仅剩下 1 个元素。因此,当您尝试访问索引 2 处的第三个元素时,您会崩溃。 If you want to delete elements serially then delete at the index 0 till the array is empty.
如果要连续删除元素,则在索引 0 处删除,直到数组为空。 So you've to delete 0 -> 0 -> 0 provided there are 3 elements in the array.
所以你必须删除 0 -> 0 -> 0 如果数组中有 3 个元素。
The issue is due to view update order.问题是由于查看更新顺序。 Use instead the following variant for
TextField
使用以下变体代替
TextField
TextField("", text: Binding(get: { self.strs[index] },
set: { self.strs[index] = $0 }))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.