You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

SwiftUI 标签与多行文本框顶部对齐异常问题求助

SwiftUI 标签与多行文本框顶部对齐异常问题求助

嗨,我来帮你搞定这个对齐问题!你遇到的核心问题是HStack默认的垂直对齐方式是居中,当右侧文本变成多行后,左边的标签容器就会被自动拉到中间位置。只需要一个简单调整就能解决:

给你的HStack添加alignment: .top参数,让两个子视图都以顶部为基准对齐,这样不管右侧文本是一行还是多行,标签都会稳稳地卡在顶部位置。

修改后的代码如下:

HStack(alignment: .top) { // 关键:设置HStack垂直对齐方式为顶部
    VStack {
        Text("Label: ")
            .lineLimit(1)
            .padding(.bottom, 20)
    }
    .background(.teal)
    
    VStack(alignment: .leading) {
        Text("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s ")
            .multilineTextAlignment(.leading)
    }
    .background(.tertiary)
}
.background(.blue)

如果之后你需要更精细的对齐控制(比如让标签稍微向下偏移一点),还可以通过alignmentGuide自定义对齐规则,但这个场景下直接设置HStack的顶部对齐就完全够用啦。

备注:内容来源于stack exchange,提问作者truthsayer

火山引擎 最新活动