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

SwiftUI中如何将ForEach生成的内容分左右两列并排显示

SwiftUI实现左右分栏显示ForEach内容

直接拆分数据源,用HStack包裹两个VStack就能实现左右并排的效果,以下是具体实现:

方案一:HStack + VStack(推荐,适配元素数量不一致)

这种方式逻辑简单,直接把数据分成左右两组,分别放在两个垂直栈里,再用水平栈并排:

struct SplitScoreView: View {
    // 拆分数据:左侧0-15,右侧16-30
    private let leftScores = Array(0...15)
    private let rightScores = Array(16...30)
    
    var body: some View {
        HStack(spacing: 30) { // 调整左右栏的间距
            // 左侧栏:显示0-15,文本红色
            VStack(alignment: .leading, spacing: 8) {
                ForEach(leftScores, id: \.self) { score in
                    Text("Score: \(score)")
                        .foregroundColor(.red)
                }
            }
            
            // 右侧栏:显示16-30,文本默认颜色
            VStack(alignment: .leading, spacing: 8) {
                ForEach(rightScores, id: \.self) { score in
                    Text("Score: \(score)")
                }
            }
        }
        .padding()
    }
}

方案二:Grid布局(适合需要严格对齐的场景)

如果需要左右每行严格对齐,即使两边元素数量不一致,用Grid实现:

struct ScoreGridView: View {
    private let allScores = Array(0...30)
    
    var body: some View {
        Grid(horizontalSpacing: 30, verticalSpacing: 8) {
            // 遍历左侧元素的索引,每行对应左右两个元素
            ForEach(0...15, id: \.self) { leftIndex in
                GridRow {
                    // 左侧元素:0-15,红色
                    Text("Score: \(leftIndex)")
                        .foregroundColor(.red)
                    
                    // 右侧元素:16-30,避免越界用安全下标
                    if let rightScore = allScores[safe: leftIndex + 16] {
                        Text("Score: \(rightScore)")
                    } else {
                        Spacer() // 最后一行右侧无元素时占位
                    }
                }
            }
        }
        .padding()
    }
}

// 给数组添加安全下标扩展,防止越界崩溃
extension Collection {
    subscript(safe index: Index) -> Element? {
        indices.contains(index) ? self[index] : nil
    }
}

为什么之前的尝试可能失败?

  • 如果直接在HStack里放一个遍历所有31个元素的ForEach,会导致所有内容横向排列,而非分两栏
  • 使用Grid时如果没正确拆分每行的元素,或者没处理两边元素数量不一致的情况,会出现布局错乱或越界问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:35:41