Search code examples
viewswiftuiscrollviewfullscreen

SwiftUI - trying to keep the fullscreen size of a View in a ScrollView


This is the source View I would like to use in another View in a Scrollview

Scrollview is compressing the view to its TextSize

SourceView:

    VStack {
        Text("Hello World")
        HStack {
            Rectangle()
                .foregroundColor(Color.blue)
            Rectangle()
                .foregroundColor(Color.green)

        }
    }

Scrollview:

    ScrollView(.horizontal) {

        HStack {

            ForEach(0 ..< 5){ item in

                worldCardView()

            }

        }
    }

Solution

  • Define a variable to retrieve the devices screen size somewhere. Place this outside of any structs so it can be accessed throughout your app.

    // Get screen dimensions for global use
    let screen = UIScreen.main.bounds
    

    And then apply a frame modifier to your rectangles.

    Rectangle()
    .frame(width: screen.width * 0.5)
    

    What I did here is to set the width of the rectangle to half of the devices screen size. Depending on the effect you're trying to achieve, you might need to add some .padding() modifiers.

    The HStack() in your ScrollView is redundant and can be removed.