【发布时间】:2021-01-26 08:53:38
【问题描述】:
我正在尝试使用编辑按钮和函数来编辑列表(由可变字符串组成)。我的代码是:
struct annotationsView: View {
@State private var text = ""
// annotations
@State var annotations : [[AnnData]] = [[]]
var body: some View {
VStack{
Form{
HStack{
TextField("Add your annotations here", text: $text)
.textFieldStyle(RoundedBorderTextFieldStyle())
Button("Submit") {
annotations[annotations.count - 1].append(AnnData(Anntext: text))
self.hideKeyboard()
text = ""
}
}
List{
ForEach(annotations.indices, id:\.self){index in
ForEach(annotations[index].indices, id:\.self){annotationIndex in
Text(annotations[index][annotationIndex].Anntext)
}.onDelete(perform: self.deleteItem) //<-- Here
}
}
}
}
.background(
Image("Background")
.resizable()
.edgesIgnoringSafeArea(.all)
.navigationBarTitle(Text("Annotations"), displayMode: .inline)
)
.navigationBarItems(trailing: EditButton())
}
private func deleteItem(at indexSet: IndexSet) {
annotations.remove(atOffsets: indexSet)
}
}
struct AnnData : Identifiable{
var id = UUID().uuidString
var Anntext: String
}
目前,我无法删除单个项目;当我删除一个时,其余的会自动删除。此外,之后我无法在列表中添加一些项目。 你介意解释一下这里出了什么问题吗? 感谢您的帮助!
【问题讨论】: