SwiftUI删除和移动功能



我的移动和删除方法遇到了一些问题。这是这个问题的后续:来自结构属性的SwiftUI部分

我正在尝试按公司对人员进行分组,上一个问题中提供的解决方案非常有效。它确实对我的移动和删除方法产生了影响,我发现很难弄清楚原因。

delete函数似乎正在删除我没有选择的行,并且move方法与Attempt to create two animations for cell.一起崩溃

struct Person: Identifiable {
var id = UUID()
var name: String
var company: String
}
class PeopleList: ObservableObject {
@Published var people = [
Person(name: "Bob", company: "Apple"),
Person(name: "Bill", company: "Microsoft"),
Person(name: "Brenda", company: "Apple"),
Person(name: "Lucas", company: "Microsoft"),
]
func getGroups() -> [String] {
var groups : [String] = []
for person in people {
if !groups.contains(person.company) {
groups.append(person.company)
}
}
return groups
}
func deleteListItem(whichElement: IndexSet) {
people.remove(atOffsets: whichElement)
}
func moveListItem(whichElement: IndexSet, destination: Int) {
people.move(fromOffsets: whichElement, toOffset: destination)
}
}
struct  ContentView: View {
@ObservedObject var peopleList = PeopleList()
var body: some View {
NavigationView {
List () {
ForEach (peopleList.getGroups(), id: .self) { group in
Section(header: Text(group)) {
ForEach(self.peopleList.people.filter { $0.company == group }) { person in
Text(person.name)
}
.onDelete(perform: self.peopleList.deleteListItem)
.onMove(perform: self.peopleList.moveListItem)
}
}
}
.listStyle(GroupedListStyle())
.navigationBarItems(trailing: EditButton())
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

更新答案-现在有了新的数据模型和工作删除

试试这个:

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")])
]
func deleteListItem(whichElement: IndexSet, from company: Company) {
let index = companies.firstIndex(of: company)!
companies[index].employees.remove(atOffsets: whichElement)
}
//    func moveListItem(whichElement: IndexSet, destination: Int) {
//        companies.employees.move(fromOffsets: whichElement, toOffset: destination)
//    }
}
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.text = ("(indexSet), (indexSet.first)")
self.companyList.deleteListItem(whichElement: indexSet, from: company)
}
//    .onMove(perform: self.companyList.moveListItem)
}
}
}
.listStyle(GroupedListStyle())
.navigationBarItems(trailing: EditButton())
Text(text)
}
}
}
}

最新更新