【发布时间】:2021-01-10 13:37:03
【问题描述】:
我试图在数组为空时显示一些占位符数据。这在 iOS 13.7 中有效,但在 iOS 14.3 中发生了一些变化,所以当最后一个项目被删除时,你会遇到这个崩溃:
致命错误:索引超出范围:文件 Swift/ContiguousArrayBuffer.swift,第 444 行
如果我注释掉 testStore.data.isEmpty 并返回 Form 我不会崩溃。
如何在 iOS 14.3 中数组为空时显示占位符?
struct Test: Identifiable {
var text: String
var id: String { text }
}
extension Test {
final class Store: ObservableObject {
@Published var data = [Test(text: "Hi"), Test(text: "Bye")]
}
}
struct TestList: View {
@EnvironmentObject var testStore: Test.Store
var body: some View {
Group {
if testStore.data.isEmpty {
Text("Empty")
} else {
Form {
ForEach(testStore.data.indices, id: \.self) { index in
TestRow(test: $testStore.data[index], deleteHandler: { testStore.data.remove(at: index) })
}
}
}
}
}
}
struct TestRow: View {
@Binding var test: Test
let deleteHandler: (() -> ())
var body: some View {
HStack {
Text(test.text)
.font(.headline)
Spacer()
Button(action: deleteHandler, label: Image(systemName: "trash"))
}
}
}
【问题讨论】:
-
@Andrew 不幸的是,没有,我搜索了所有 SO 无济于事。欢迎您自己尝试代码。
-
删除绑定,而不是这个传递 testStore 对象和索引
-
这能回答你的问题吗? Deleting list elements from SwiftUI's List
标签: ios arrays swift list swiftui