[英].ondelete SwiftUI List with Sections
我無法發布用於在 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 方法,因為我不能在結構中使用變異方法。 如何更改我的代碼以添加用於刪除和移動帶節列表中的項目的功能?
您需要為您的函數使用mutating
修飾符,並更新代碼
struct Category: Identifiable {
// ... other code
mutating func deleteListItem(_ whichElement: IndexSet) {
items.remove(atOffsets: whichElement)
}
mutating func moveListItem(_ whichElement: IndexSet, _ destination: Int) {
items.move(fromOffsets: whichElement, toOffset: destination)
}
}
和用法像
.onDelete { indexSet in
checklist.items[category.number].deleteListItem(indexSet)
}
.onMove { indexSet, dest in
checklist.items[category.number].moveListItem(indexSet, dest)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.