0

我正在尝试制作两个Text在 a 内的VStack以占据父级(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

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

在此处输入图像描述

4

2 回答 2

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

最终结果将是:

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

改为使其左对齐:

HStack {
     Text("title")
        .font(.title)
                    
        Spacer(minLength: 0)
}
.background(Color.red)
于 2020-09-04T03:47:51.153 回答
0

这是可能的解决方案

        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 
于 2020-09-04T04:16:04.160 回答