use geometryreader to make a scrollview open from the right side in swift

You can use GeometryReader to get the geometry of the parent view and then use it to set the size of the child view. Here's an example of how to create a ScrollView that opens from the right side using GeometryReader:

main.swift
struct ContentView: View {
    var body: some View {
        GeometryReader { geometry in
            ScrollView(.horizontal) {
                HStack {
                    ForEach(0..<10) { index in
                        Rectangle()
                            .fill(Color.blue)
                            .frame(width: geometry.size.width / 2, height: geometry.size.height)
                    }
                }
            }
            .frame(width: geometry.size.width, height: geometry.size.height)
            .contentShape(Rectangle())
            .offset(x: geometry.size.width, y: 0)
        }
    }
}
617 chars
19 lines

In the code above, we create a GeometryReader to get the geometry of the parent view. We then create a ScrollView with a horizontal axis and inside it a HStack to display multiple rectangles. In the ForEach loop, we create a Rectangle with width equal to half of the parent view's width and height equal to the parent view's height.

We set the frame of the ScrollView to be equal to the parent view's geometry size, and then set the contentShape to a Rectangle to make the entire area clickable. We also set the offset of the ScrollView to be equal to the parent view's width to make it initially hidden.

The result is a ScrollView that opens from the right side when it appears.

related categories

gistlibby LogSnag