如何在分组列表中实现 onMove 函数?不幸的是,我看不到我从哪里得到“到公司”的信息......
这是代码:
import SwiftUI
struct Person: Identifiable, Hashable {
var id = UUID()
var name: String
}
struct Company : Identifiable, Hashable {
var id = UUID()
var name: String
var employees : [Person]
}
class CompanyList: ObservableObject {
@Published var companies = [
Company(name: "Apple", employees: [Person(name:"Bob"), Person(name:"Brenda")]),
Company(name: "Microsoft", employees: [Person(name:"Bill"), Person(name:"Lucas")]),
Company(name: "Facebook", employees: [Person(name:"Mark"), Person(name:"Sandy")])
]
func deleteListItem(whichElement: IndexSet, from company: Company) {
let index = companies.firstIndex(of: company)!
companies[index].employees.remove(atOffsets: whichElement)
}
func moveListItem(whichElement: IndexSet, to companyIndex: Int) {
print(whichElement.first)
if whichElement.count > 1 {
whichElement.dropFirst()
print(whichElement.first)
}
print(companyIndex)
// let employee = companies[index].employees[whichElement.first!]
// companies[index].employees.remove(at: whichElement.first!)
//
}
}
struct ContentView: View {
@ObservedObject var companyList = CompanyList()
@State var text : String = ""
var body: some View {
NavigationView {
VStack {
List () {
ForEach (companyList.companies, id: \.self) { company in
Section(header: Text(company.name)) {
ForEach(company.employees) { employee in
Text(employee.name).id(UUID())
}
.onDelete { (indexSet) in
self.companyList.deleteListItem(whichElement: indexSet, from: company)
}
.onMove { indexSet, intValue in
self.companyList.moveListItem(whichElement: indexSet, to: intValue)
}
.onInsert(of: ["chris"]) { (intValue, _) in
print("wtf")
}
}
}
}
.listStyle(GroupedListStyle())
.navigationBarItems(trailing: EditButton())
}
}
}
}