在SwiftUI,SwiftUI中调整多个vstack宽度

时间:2020-10-06 18:48:46

标签: swift swiftui vstack hstack

我有一个VStack

VStack(alignment: .leading) {
        Text(question)
            .fontWeight(.heavy)
            .font(.system(.footnote, design: .rounded))
            .padding(.bottom)
        Text(answer)
            .fontWeight(.semibold)
            .font(.system(.title, design: .rounded))
    }
    .padding(35)
    .overlay(RoundedRectangle(cornerRadius: 12).stroke(Color("darkGrey"), lineWidth: 2))
    .padding([.leading,.top,.trailing])
    .frame(minWidth: UIScreen.main.bounds.width - 5,
           minHeight: 50,
           maxHeight: .infinity,
           alignment: .topLeading
    )

我在View中使用它,例如:

ScrollView(.horizontal, showsIndicators: false) {
                Group {
                    HStack {
                        questionCard(question: "Cats or Dogs", answer: "Dogs")
                        questionCard(question: "Cats or Dogs", answer: "Dogs")
                    }
                }
            }

结果如下:

enter image description here

我试图将框的width移到屏幕的末尾(具有.trailing的空格),然后当我滚动到下一个时,它的宽度应该相同。 / p>

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

struct ContentView: View {
    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            Group {
                HStack {
                    QuestionCard(question: "Cats or Dogs", answer: "Dogs")
                    QuestionCard(question: "Cats or Dogs", answer: "Dogs")
                }
            }
        }
    }
}
struct QuestionCard: View {
    let question: String
    let answer: String
    
    var body: some View {
        
        HStack {
            Spacer()
            VStack(alignment: .leading) {//<- Change the alignment if needed
                Text(question)
                    .fontWeight(.heavy)
                    .font(.system(.footnote, design: .rounded))
                    .padding(.bottom)
                Text(answer)
                    .fontWeight(.semibold)
                    .font(.system(.title, design: .rounded))
            }
            Spacer()
            
        }
        .padding(35)
        .overlay(RoundedRectangle(cornerRadius: 12).stroke(Color.black, lineWidth: 2))
        .padding([.leading, .top, .trailing])
        .frame(minWidth: UIScreen.main.bounds.width - 5,
               minHeight: 50,
               maxHeight: .infinity,
               alignment: .top
        )
    }
}

因此,基本上,我只是使用HStack和两个Spacers来使用所有可用空间。 看起来像这样:
enter image description here