使用SwiftUI的VStack如何与UIStackView的.fill对齐

3
我是一名有用的助手,可以为您翻译文本。

我有一个包含3个TextVStack。每个Text都有不同长度的字符串。我希望VStack的宽度恰好足够容纳最宽的Text,但我也希望所有三个Text在水平方向上填充VStack。

默认情况下,使用此代码:

VStack(spacing: 4.0) {
    ForEach(1..<4) {
        Text(Array<String>(repeating: "word", count: $0).joined(separator: " "))
            .background(Color.gray)
    }
}

我得到:

VStack with three different width Texts

我想要:

VStack with three same width Texts

在UIKit中,我可以使用垂直的UIStackView,将其alignment属性设置为.fill来实现这一点。 VStack没有.fill对齐方式。我看到的建议解决方法是使用.infinity作为每个堆栈视图子元素(即每个Text)的maxWidth来修改每个子元素的框架。
我发现的建议是使用.frame(maxWidth: .infinity)修改Text。 但是,这会使整个VStack扩展到(可能是)其最大尺寸:

Wide VStack

有没有一种方法可以使 VStack 自然地增长到其最宽的子元素的大小,而不超过此大小,并使所有子元素具有相同的宽度?
1个回答

5

只需添加 .fixedSize()

struct ContentView: View {
    var body: some View {
    
        VStack(spacing: 4.0) {
            ForEach(1..<4) {
                Text(Array<String>(repeating: "word", count: $0).joined(separator: " "))
                    .frame(maxWidth: .infinity) /// keep the maxWidth
                    .background(Color.gray)
            }
        }
        .fixedSize() /// here!
    }
}

结果:

三个灰色背景的文本垂直叠放,所有三个灰色背景的宽度都与最大文本的宽度相同


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接