使 VStack 中的文本占据 VStack 的整个宽度

Make Text inside VStack take the whole width of the VStack

我正在尝试在 VStack 中创建两个 Text 以占用父级(VStack)的整个宽度。

我完全没有想法。

这是我的:

var body: some View {
        VStack(alignment: .center, spacing: 0) {

            Image("image")
                .resizable()
                .scaledToFill()
                .frame(height: 190)
                .clipped()

            VStack(alignment: .leading, spacing: 8) {
                Text(title)
                    .font(.title)
                    .background(Color.red)
                    .fixedSize(horizontal: false, vertical: true)

                Text(subtitle)
                    .font(.subheadline)
                    .background(Color.yellow)
                    .fixedSize(horizontal: false, vertical: true)
            }
                .frame(minWidth: 0, maxWidth: .infinity)
                .background(Color.green)
                .padding(.top, 24)
                .padding(.horizontal, 24)


            Button(buttonTitle) { print("Something") }
                .frame(maxWidth: .infinity, minHeight: 56)
                .background(Color.red)
                .foregroundColor(.white)
                .cornerRadius(56/2)
                .padding(.top, 32)
                .padding(.horizontal, 24)
                .padding(.bottom, 20.0)

        }.background(Color.blue)
            .cornerRadius(38)
            .frame(minWidth: 0, maxWidth: UIScreen.main.bounds.size.width - 48)
}

这是它的样子:

我想让红色和黄色标签占据绿色的整个宽度VStack

我怎样才能做到这一点?!

  1. 删除两个文本上的 .fixedSize
  2. 改为添加 .frame(minWidth: 0, maxWidth: .infinity)
  3. 在 SwiftUI 中,事物的顺序也很重要,因此您需要在 .frame 之后添加 .background

最终结果为:

            Text("title")
                .font(.title)
                .frame(minWidth: 0, maxWidth: .infinity)
                .background(Color.red)

改为左对齐:

HStack {
     Text("title")
        .font(.title)
                    
        Spacer(minLength: 0)
}
.background(Color.red)

这是可能的解决方案

        VStack(alignment: .leading, spacing: 8) {
            Text(title)
                .font(.title)
                .frame(maxWidth: .infinity)    // << here 
                .background(Color.red)
                .fixedSize(horizontal: false, vertical: true)

            Text(subtitle)
                .font(.subheadline)
                .frame(maxWidth: .infinity)    // << here
                .background(Color.yellow)
                .fixedSize(horizontal: false, vertical: true)
        }
        .frame(maxWidth: .infinity)   // << here