iosscrollviewswiftuihorizontallisthstack

Full Screen View not working inside HStack and Horizontal ScrollView


I have been trying to create onboarding flow using horizontal lists etc. I have created a view called OnboardingViewand inside it I have a VStack with image, and two Text views.

struct OnboardingView: View {
var body: some View {
    GeometryReader { geometry in
        VStack(spacing: 10) {
            Spacer()
            Image("1")
                .resizable()
                .frame(width: 300, height: 300)
                .clipShape(Circle())
                .padding(20)
            Text("Travel the World")
                .frame(width: geometry.size.width, height: 20, alignment: .center)
                .font(.title)
            Text("Explore the world and get to know different cultures and people from all around the world")
                .lineLimit(nil)
                .padding(.leading, 15)
                .padding(.trailing, 15)
                .font(.system(size: 16))
                .frame(width: geometry.size.width, height: 50, alignment: .center)
                .multilineTextAlignment(.center)
            Spacer()

        }.background(Color.red)
}

} }

This is what I get with the above code:

enter image description here

Now I am trying to add this view inside a ScrollView, using HStack.

struct ContentView: View {

var body: some View {
   ScrollView(.horizontal, showsIndicators: false) {
        HStack {
            OnboardingView()
            OnboardingView()
        }
    }.background(Color.black)

  }
 }

The result of the above code is absurd! This is what I get. How to go about fixing this? Help will be appreciated! Thanks.

enter image description here


Solution

  • One possible solution would be to set the width of the OnboardingView to geometry.size.width:

    var body: some View {
        GeometryReader { geometry in
            ScrollView(.horizontal, showsIndicators: false) {
                HStack {
                    OnboardingView()
                        .frame(width: geometry.size.width)
                    OnboardingView()
                        .frame(width: geometry.size.width)
                }
            }.background(Color.black)
        }
    }
    

    Result

    width