Sizing multiple vstack width in scroll view, SwiftUI

338 views Asked by At

I have a 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
    )

And Im using it in my View like:

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

This results in the following:

enter image description here

I'm trying to get the width of the box to the end of the screen (with .trailing space) and then when I scroll to the next, it should be the same width.

1

There are 1 answers

0
finebel On BEST ANSWER

You could do something like the following:

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
        )
    }
}

So basically I`m just using an HStack and two Spacers in order to use all of the available space. It looks like this:
enter image description here