You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI List中如何获取Section行数并显示在头部

解决SwiftUI List Section头部显示对应行数的问题

核心思路是提前过滤出当前Section需要展示的员工子集,这样既能直接获取子集的数量用于头部显示,还能简化视图层的条件判断逻辑:

  • 先在Day1View里添加一个计算属性,专门筛选出早班的员工:
    var earlyShiftEmployees: [Employee] {
        displayEmployees.filter { $0.shift == .early }
    }
    
  • 然后Section头部直接使用这个子集的count值,同时ForEach直接遍历这个子集,不用再写if employee.shift == .early的判断:

修改后的完整代码:

struct Day1View: View {
    var displayEmployees: [Employee]
    
    // 提前过滤早班员工
    var earlyShiftEmployees: [Employee] {
        displayEmployees.filter { $0.shift == .early }
    }
    
    var body: some View {
        List {
            Section(header: Text("Early (\(earlyShiftEmployees.count))")) {
                ForEach(earlyShiftEmployees) { employee in
                    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)
                    }
                }
            }
        }
    }
}

这样做的好处:

  1. 避免在视图循环里做条件判断,代码结构更清晰
  2. 直接通过子集的count拿到准确的行数,完全符合需求
  3. 计算属性是懒加载的,只会在displayEmployees变化时重新计算,性能不受影响

内容的提问来源于stack exchange,提问作者AvsBest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 04:50:36