use geometryreader to make a scrollview move right in swift

You can use GeometryReader and ScrollView to achieve this. Here's an example:

main.swift
struct ContentView: View {
    var body: some View {
        GeometryReader { geometry in
            ScrollView(.horizontal, showsIndicators: false) {
                HStack {
                    ForEach(0..<10) { index in
                        Text("Item \(index+1)")
                            .frame(width: geometry.size.width, height: 200)
                            .background(Color.blue)
                    }
                }
            }
        }
    }
}
472 chars
16 lines

In this example, the GeometryReader provides the width of the screen. The ScrollView is set to scroll horizontally and the contents inside it are wrapped inside an HStack. The ForEach loop is used to populate the HStack with Text views.

Each Text view is given a width equal to the width of the screen (geometry.size.width) and a height of 200 points. The background modifier is used to set a blue background for each view.

Now when you run the app and swipe left or right, the ScrollView will move in the desired direction.

related categories

gistlibby LogSnag