假设我有
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"),
]
//Various delete and move methods
}
我现在想创建一个包含部分的列表,其中每个人都根据他们的公司进行分组。我已经了解了以下内容,但这为我提供了每个人的分组部分,即 4 个部分。我希望最终分为 2 个部分,一节针对 Apple,一节针对 Microsoft。
struct PeopleView: View {
@ObservedObject var peopleList = PeopleList()
var body: some View {
NavigationView {
List {
ForEach(peopleList.people) { person in
Section(header: Text(person.company)) {
Text(person.name)
}
}
}
.listStyle(GroupedListStyle())
}
}
}
我希望这是有道理的!谢谢!
最佳答案
试试这个:
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
}
}
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)
}
}
}
}.listStyle(GroupedListStyle())
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
关于结构体属性中的 SwiftUI 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61577342/