将 UIStackView 的 .fill 与 SwiftUI VStack 对齐
Match UIStackView's .fill alignment with SwiftUI VStack
我有一个 VStack
,里面有 3 个 Text
。每个都有不同长度的字符串。我希望 VStack
的宽度刚好足以容纳最宽的 Text
,但我也希望所有三个 Text
水平填充 VStack。
默认情况下,使用此代码:
VStack(spacing: 4.0) {
ForEach(1..<4) {
Text(Array<String>(repeating: "word", count: [=10=]).joined(separator: " "))
.background(Color.gray)
}
}
我得到:
我要:
在 UIKit 中,我可以使用垂直 UIStackView
来做到这一点,其 alignment
属性 设置为 .fill
。 VStack
没有 .fill
对齐。我看到的建议解决方案是将堆栈视图的每个 child 的框架(即每个 Text
)修改为 .infinity
for maxWidth
.
我发现的建议是将 Text
修改为 .frame(maxWidth: .infinity)
。然而,这使得整个 VStack
扩展到(大概)它的最大尺寸:
有没有办法让 VStack
自然增长到其最宽 child 的大小,而不是更大,同时使其所有 children 宽度相同?
只需添加 .fixedSize()
.
struct ContentView: View {
var body: some View {
VStack(spacing: 4.0) {
ForEach(1..<4) {
Text(Array<String>(repeating: "word", count: [=10=]).joined(separator: " "))
.frame(maxWidth: .infinity) /// keep the maxWidth
.background(Color.gray)
}
}
.fixedSize() /// here!
}
}
结果:
我有一个 VStack
,里面有 3 个 Text
。每个都有不同长度的字符串。我希望 VStack
的宽度刚好足以容纳最宽的 Text
,但我也希望所有三个 Text
水平填充 VStack。
默认情况下,使用此代码:
VStack(spacing: 4.0) {
ForEach(1..<4) {
Text(Array<String>(repeating: "word", count: [=10=]).joined(separator: " "))
.background(Color.gray)
}
}
我得到:
我要:
在 UIKit 中,我可以使用垂直 UIStackView
来做到这一点,其 alignment
属性 设置为 .fill
。 VStack
没有 .fill
对齐。我看到的建议解决方案是将堆栈视图的每个 child 的框架(即每个 Text
)修改为 .infinity
for maxWidth
.
我发现的建议是将 Text
修改为 .frame(maxWidth: .infinity)
。然而,这使得整个 VStack
扩展到(大概)它的最大尺寸:
有没有办法让 VStack
自然增长到其最宽 child 的大小,而不是更大,同时使其所有 children 宽度相同?
只需添加 .fixedSize()
.
struct ContentView: View {
var body: some View {
VStack(spacing: 4.0) {
ForEach(1..<4) {
Text(Array<String>(repeating: "word", count: [=10=]).joined(separator: " "))
.frame(maxWidth: .infinity) /// keep the maxWidth
.background(Color.gray)
}
}
.fixedSize() /// here!
}
}
结果: