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

如何在SwiftUI List中动态展示所有Service对应的ServiceElementView?

解决方案

你可以用SwiftUI的ForEach遍历month.services数组,动态生成对应的ServiceElementView,替换掉原来手动添加的视图:

var body: some View {
    NavigationView {
        List {
            MonthElementView(month: month)
            // 遍历所有service生成对应视图
            ForEach(month.services) { service in
                ServiceElementView(service: service)
            }
        }
    }
}

注意事项

  • 如果你的Service类型未遵循Identifiable协议,需要在ForEach中指定唯一标识(前提是Service为可哈希的值类型):
    ForEach(month.services, id: \.self) { service in
        ServiceElementView(service: service)
    }
    
  • 更规范的做法是让Service遵循Identifiable协议,这样ForEach能自动识别唯一ID:
    struct Service: Identifiable {
        let id = UUID() // 也可以使用业务逻辑中的唯一标识字段
        // 其他属性定义
    }
    

修改后,month.services中的每一个Service都会自动对应生成一个ServiceElementView,无需手动逐个添加。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:51:37