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

SwiftUI中HStack内TextField对齐与尺寸统一问题求助

解决方案

要让两个TextField尺寸完全一致且精准对齐,核心是让左侧的Text组件占据相同宽度,这样右侧的TextField就能获得等量的剩余空间。具体修改如下:

修改后的代码

VStack {
    HStack {
        Text("Voorfietskosten:")
            .frame(minWidth: 180, alignment: .leading) // 固定Text最小宽度,保持左对齐
            .padding()
            .font(.custom("Rubik-Light_Medium", size: 18))
            .foregroundColor(Color("Charcoal"))
        TextField("Voorfietskosten", value: $ccControler.amountBikingCosts, format: .currency(code: "EUR"))
            .keyboardType(.decimalPad)
            .foregroundColor(Color("Charcoal"))
            .padding()
            .background(Color.white)
            .cornerRadius(10)
            .padding(.horizontal)
    }
    .padding(.horizontal)
    
    HStack {
        Text("Tarief kwartier:")
            .frame(minWidth: 180, alignment: .leading) // 和上方Text保持相同最小宽度
            .padding()
            .font(.custom("Rubik-Light_Medium", size: 18))
            .foregroundColor(Color("Charcoal"))
        TextField("Tarief per kwartier", value: $ccControler.amountEachQuarterTime, format: .currency(code: "EUR"))
            .keyboardType(.decimalPad)
            .foregroundColor(Color("Charcoal"))
            .padding()
            .background(Color.white)
            .cornerRadius(10)
            .padding(.horizontal)
    }
    .padding(.horizontal)
}

原理说明

  • 默认HStack会根据子视图内容长度分配空间,左侧Text长度差异会导致右侧TextField的可用宽度不一致。
  • 给两个Text设置相同的minWidth,强制它们占据等量宽度,右侧TextField就能自动填充剩余的相同空间,实现尺寸一致和上下对齐。
  • 你可以根据实际布局需求调整180这个数值,确保所有Text都能完整显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 13:52:39