使VStack中的文本占据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

解决方法

  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 

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...