本文介绍了将 UIStackView 的 .fill 对齐与 SwiftUI VStack 匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 VStack,里面有 3 个 Text .每个都有不同长度的字符串.我希望 VStack 的宽度足够大以适合最宽的 Text,但我也希望所有三个 Texts 水平填充 VStack.

I've got a VStack with 3 Texts in it. Each has a different length string. I'd like the VStack's width to be just big enough to fit the widest Text, but I'd also like all three Texts to fill the VStack horizontally.

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

By default, with this code:

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

我明白了:

我想要:

在 UIKit 中,我可以用一个垂直的 UIStackView 来做到这一点,它的 alignment 属性被设置为 .fill.VStack 没有 .fill 对齐.我看到的建议解决方案是使用 .infinitymaxWidth 修改堆栈视图的每个子项(即每个 Text)的框架>.

In UIKit, I could do this with a vertical UIStackView whose alignment property was set to .fill. VStack doesn't have a .fill alignment. The suggested solution I've seen is to modify the frame of each child of the stack view (ie. each Text) with .infinity for maxWidth.

我发现的建议是用 .frame(maxWidth: .infinity) 修改 Texts.然而,这使得整个 VStack 扩展到(大概)它的最大大小:

The suggestion I've found is to modify the Texts with .frame(maxWidth: .infinity). However, this makes the whole VStack expand to (presumably) its maximum size:

有没有办法让 VStack 自然地增长到它最宽的孩子的大小,而不是更大,同时让所有孩子的宽度相同?

Is there a way to make the VStack naturally grow to the size of its widest child, and no larger, while making all its children the same width?

推荐答案

只需添加.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!
    }
}

结果:

这篇关于将 UIStackView 的 .fill 对齐与 SwiftUI VStack 匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-31 15:00