结构体属性中的 SwiftUI 部分

标签 swift swiftui

假设我有

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()
    }
}

enter image description here

关于结构体属性中的 SwiftUI 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61577342/

相关文章:

swift - 在带有 M1 芯片的 Xcode 12 的范围内找不到类型 '*'

ios - CKReference 列表更新

iOS 13 在后台关闭应用程序 : Audio Stream Issue

swift - 将可选绑定(bind)转换为非可选绑定(bind)

swiftui - 应用 onLongPress 修饰符时,使用 NavigationLink 进行点击导航被破坏

ios - 从 UIPickerview 获取文本并在 UIAlert 中移动 Textfield

swift - 通过快速将 NSDictionary 添加到 NSMutableArray 来更改数据

iOS Firebase 动态链接未在冷启动 iOS 14 上处理

swiftui - 在 SwiftUI Mac 应用程序列表中删除右键单击行的轮廓

ios - 在 View 外部触发时如何绑定(bind) SwiftUI.Alert 的呈现?