【问题标题】:Match UIStackView's .fill alignment with SwiftUI VStack将 UIStackView 的 .fill 对齐与 SwiftUI VStack 匹配
【发布时间】:2021-07-21 05:55:06
【问题描述】:

我有一个 VStack,其中包含 3 个 Texts。每个都有不同长度的字符串。我希望VStack 的宽度刚好足以容纳最宽的Text,但我还希望所有三个Texts 都水平填充VStack。

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

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

我明白了:

我想要:

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

我发现的建议是将Texts 修改为.frame(maxWidth: .infinity)。但是,这会使整个 VStack 扩展到(可能)它的最大尺寸:

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

【问题讨论】:

    标签: ios swift swiftui vstack


    【解决方案1】:

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

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-29
      • 1970-01-01
      • 2021-03-29
      • 2021-01-01
      • 2020-12-07
      • 1970-01-01
      • 2020-05-16
      • 2019-12-27
      相关资源
      最近更新 更多