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

SwiftUI如何垂直对齐Text视图实现规范对齐的类表格布局且支持iOS13

适配iOS13的表格列对齐解决方案

核心思路是给每列单元格设置均等宽度+统一对齐规则,无需手动调整间距,可适配所有屏幕尺寸和动态内容。

具体修改点

  • 移除表头和行视图HStack的手动spacing参数
  • 给每一列的表头文本、行内容文本都添加frame(maxWidth: .infinity, alignment: .center)修饰符,让HStack自动均分宽度,同一列内容对齐方式统一
  • 移除冗余的Spacer,三列已经自动撑满整个宽度

完整修改后代码

struct ContentView: View {
    var body: some View {
        VStack(spacing: 0) {
            ZStack {
                TitleBackground()
                Text("Clients")
                    .foregroundColor(.white)
            }
            // 表头
            HStack {
                Text("Name")
                    .frame(maxWidth: .infinity, alignment: .center)
                Text("Balance")
                    .frame(maxWidth: .infinity, alignment: .center)
                Text("Currency")
                    .frame(maxWidth: .infinity, alignment: .center)
            }
            .foregroundColor(Color(#colorLiteral(red: 0.4783782363, green: 0.4784628153, blue: 0.4783664346, alpha: 1)))
            .padding(12)
            .background(Color(#colorLiteral(red: 0.9332349896, green: 0.9333916306, blue: 0.9332130551, alpha: 1)))
            
            RowView()
            RowView()
            RowView()
            RowView()
        }
    }
}

struct RowView : View {
    var body: some View {
        HStack {
            Text("John")
                .frame(maxWidth: .infinity, alignment: .center)
            Text("$5300")
                .frame(maxWidth: .infinity, alignment: .center)
            Text("EUR")
                .frame(maxWidth: .infinity, alignment: .center)
        }
        .padding(12)
    }
}

struct TitleBackground: View {
    var body: some View {
        ZStack(alignment: .bottom){
            Rectangle()
                .frame(maxWidth: .infinity, maxHeight: 60)
                .foregroundColor(.red)
                .cornerRadius(15)
            // 仅保留顶部圆角,底部用矩形覆盖圆角
            Rectangle()
                .frame(maxWidth: .infinity, maxHeight: 15)
                .foregroundColor(.red)
        }
    }
}

可选自定义调整

如果不需要三列均分宽度,比如希望Balance列占比更大,可以通过GeometryReader获取父容器宽度,手动指定每列的宽度比例,示例如下:

// 示例:Name占25%、Balance占50%、Currency占25%
GeometryReader { proxy in
    HStack {
        Text("Name")
            .frame(width: proxy.size.width * 0.25, alignment: .center)
        Text("Balance")
            .frame(width: proxy.size.width * 0.5, alignment: .center)
        Text("Currency")
            .frame(width: proxy.size.width * 0.25, alignment: .center)
    }
}

这种方式同样完全兼容iOS13,对齐效果稳定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:36:04