【问题标题】:How to get a row count in SwiftUI List如何在 SwiftUI 列表中获取行数
【发布时间】:2022-12-31 01:45:26
【问题描述】:

我正在尝试在其标题的某个部分中显示行数,如下所示为 COUNTHERE。我遇到的问题是我不能在 if 语句中放入任何不是视图的代码,所以我无法计算任何东西。想法?

struct Day1View: View {

var displayEmployees: [Employee]

var body: some View {
    List {
        Section(header: Text("Early (\(COUNTHERE)")) {
            ForEach(displayEmployees) { employee in
                if employee.shift == .early {
                    switch employee.post {
                    case .kitchen : Text(employee.name).foregroundColor(.blue)
                    case .floor : Text(employee.name).foregroundColor(.yellow)
                    case .upstairs : Text(employee.name).foregroundColor(.red)
                    case .greeting : Text(employee.name).foregroundColor(.green)
                    default : Text(employee.name).foregroundColor(.gray)
                    }
                }
            }
        }
     }

【问题讨论】:

    标签: list swiftui count row


    【解决方案1】:

    要显示节标题中的行数,您可以使用 @State 属性包装器来存储节中的行数,并在 displayEmployees 数组更改时更新它。

    以下是如何执行此操作的示例:

    复制代码 结构 Day1View:视图 { var displayEmployees:[员工]

    @State private var earlyShiftCount: Int = 0
    
    var body: some View {
        List {
            Section(header: Text("Early ((earlyShiftCount)")) {
                ForEach(displayEmployees) { employee in
                    if employee.shift == .early {
                        switch employee.post {
                        case .kitchen : Text(employee.name).foregroundColor(.blue)
                        case .floor : Text(employee.name).foregroundColor(.yellow)
                        case .upstairs : Text(employee.name).foregroundColor(.red)
                        case .greeting : Text(employee.name).foregroundColor(.green)
                        default : Text(employee.name).foregroundColor(.gray)
                        }
                    }
                }
                .onChange(of: displayEmployees) { value in
                    self.earlyShiftCount = value.filter { $0.shift == .early }.count
                }
            }
        }
    }
    

    } 在此示例中,earlyShiftCount 状态变量初始化为 0,并在 displayEmployees 数组使用 onChange 修饰符更改时更新。然后使用字符串插值将 earlyShiftCount 变量显示在节标题中。

    我希望这有帮助!如果您有任何问题,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      相关资源
      最近更新 更多