Swiftui 指数不';从列表中删除项目时不更新
我想创建一个视图,我可以将数组传递到该视图中,并让该视图编辑该数组。以下代码是一个简化示例:Swiftui 指数不';从列表中删除项目时不更新,swiftui,Swiftui,我想创建一个视图,我可以将数组传递到该视图中,并让该视图编辑该数组。以下代码是一个简化示例: struct Item: Identifiable { var name: String var id = UUID() } struct EditItems: View { @Binding var item_list: [Item] var body: some View { List { ForEach(item_list.indices) { idx
struct Item: Identifiable {
var name: String
var id = UUID()
}
struct EditItems: View {
@Binding var item_list: [Item]
var body: some View {
List {
ForEach(item_list.indices) { idx in
Text(item_list[idx].name)
}
.onDelete(perform: deleteItem)
}
.toolbar {
ToolbarItem(placement: .principal) {
EditButton()
}
}
}
func deleteItem(at offsets: IndexSet) {
item_list.remove(atOffsets: offsets)
}
}
这将编译并最初运行。我可以点击“编辑”并删除列表项。删除列表项后,当我点击“完成”时,我得到“致命错误:索引超出范围”。调试器告诉我,我的列表有7项,但行文本(item_list[idx].name)
正试图使用idx=7执行
因此,删除项目后,ForEach
似乎仍在运行旧索引,而不是新索引。这是因为项目列表
不是@状态
?当我尝试同时使用@State
和@Binding
时,我遇到了一系列错误
如何解决此问题?接受范围的ForEach
的初始值设定项只能用于常量数据
发件人:
实例只读取所提供数据的初始值,并
不需要跨更新标识视图
使用另一个ForEach
初始值设定项,例如:
ForEach(item_list.enumerated(), id: \.self) { idx, element in
接受范围的ForEach
的初始值设定项只能用于常量数据
发件人:
实例只读取所提供数据的初始值,并
不需要跨更新标识视图
使用另一个ForEach
初始值设定项,例如:
ForEach(item_list.enumerated(), id: \.self) { idx, element in
您使用了ForEach
的构造函数,该构造函数创建了常量容器,使用不同的构造函数,带有显式标识符,如
List {
ForEach(item_list.indices, id: \.self) { idx in // << here !!
Text(item_list[idx].name)
}
列表{
ForEach(item\u list.index,id:\.self){idx in/您使用了ForEach
的构造函数,该构造函数创建常量容器,使用不同的容器,带有显式标识符,如
List {
ForEach(item_list.indices, id: \.self) { idx in // << here !!
Text(item_list[idx].name)
}
列表{
ForEach(item\u list.index,id:\.self){idx in//我会的,我从来没有注意到其中一些是常量,而另一些不是常量。谢谢!我会的,我从来没有注意到其中一些是常量,而另一些不是常量。谢谢!