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

SwiftUI枚举列表仅单行显示问题:为何无法逐行展示枚举项

问题原因及解决方案

原因分析

你遇到的问题是因为在List中嵌套了另一个List:ContentView里的List包含Section,而Section中直接放入了带有List的DisplayRow。SwiftUI中,当List作为另一个List的子视图时,会被系统当作单个列表项处理,内部的List不会展开显示所有行,只会被压缩成一行。

解决方案

解决核心是避免List嵌套,改用ForEach生成行项序列,因为ForEach是SwiftUI专门用来生成视图序列的组件,能被List正确识别为多个独立行。

方案1:修改DisplayRow为返回ForEach

将DisplayRow内部的List替换为ForEach,这样它会生成多个行视图,而非嵌套List:

struct DisplayRow: View {
    var body: some View {
        ForEach(0..<flaps.allCases.count, id: \.self) { index in
            HStack {
                Text(flaps.allCases[index].rawValue)
                    .frame(maxWidth: .infinity, alignment: .leading)
                Text(woundscode.allCases[index].rawValue)
            }
            .padding(.all)
            .border(Color.gray)
        }
    }
}

ContentView的代码保持不变,此时Section会正确渲染DisplayRow里的所有行项。

方案2:直接在ContentView的Section中遍历

如果DisplayRow没有复用需求,也可以直接在Section内用ForEach生成行项,省去嵌套:

struct ContentView: View {
    var body: some View {
        List {
            Section(header: Text("Flaps")) {
                ForEach(0..<flaps.allCases.count, id: \.self) { index in
                    HStack {
                        Text(flaps.allCases[index].rawValue)
                            .frame(maxWidth: .infinity, alignment: .leading)
                        Text(woundscode.allCases[index].rawValue)
                    }
                    .padding(.all)
                    .border(Color.gray)
                }
            }
            Section(header: Text("test")) {
                Text("2")
                Text("3")
            }
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 02:01:16