【发布时间】:2020-10-19 12:30:27
【问题描述】:
我无法在 SwiftUI 列表中发布删除和移动行的方法。
我有类别的模型:
struct Category: Identifiable {
var id = UUID()
var title: String
var number: Int
var items: [ChecklistItem]
func deleteListItem(whichElement: IndexSet) {
items.remove(atOffsets: whichElement)
}
func moveListItem(whichElement: IndexSet, destination: Int) {
items.move(fromOffsets: whichElement, toOffset: destination)
}
}
清单项目:
struct ChecklistItem: Identifiable {
let id = UUID()
var name: String
var isChecked = false
}
和清单:
class Checklist: ObservableObject {
@Published var items = [Category]()
}
这是我的列表视图:
struct ChecklistView: View {
@EnvironmentObject var checklist: Checklist
@State var newChecklistItemViewIsVisible = false
var body: some View {
NavigationView {
List {
ForEach(checklist.items) { category in
Section(header: Text(category.title)) {
ForEach(category.items) { item in
HStack {
Text(item.name)
Spacer()
Text(item.isChecked ? "✅" : "????")
}
.background(Color.white)
.onTapGesture {
if let matchingIndex =
checklist.items[category.number].items.firstIndex(where: { $0.id == item.id }) {
checklist.items[category.number].items[matchingIndex].isChecked.toggle()
}
}
}
.onDelete(perform: checklist.items[category.number].deleteListItem)
.onMove(perform: checklist.items[category.number].moveListItem)
}
}
}
.navigationBarItems(
leading: Button(action: {
self.newChecklistItemViewIsVisible = true
}) {
HStack {
Image(systemName: "plus.circle.fill")
Text("Add")
}
},
trailing: EditButton()
)
.navigationBarTitle("List")
}
.onAppear {
//print("ContentView appeared!")
}
.sheet(isPresented: $newChecklistItemViewIsVisible) {
NewChecklistItemView(checklist: self.checklist)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ChecklistView()
}
}
我不能使用 .ondelete 和 .onmove 方法,因为我不能在 struct 中使用变异方法。如何更改我的代码以添加功能以删除和移动 List with Sections 中的项目?
【问题讨论】: