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

时间:2020-09-04 03:32:19

标签: swift swiftui vstack

我正在尝试在Text内制作两个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的整个宽度。

我该如何实现?!

enter image description here

2 个答案:

答案 0 :(得分:1)

  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)

答案 1 :(得分: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