SwiftUI: ScrollView with paging scrollTargetBehavior shows end of previous page in current page

411 views Asked by At

I’m trying to show a list of pictures in my app using ScrollView and .scrollTargetBehavior(.paging) modifier. But when swipe to next page, the view does not start at the beginning of the next image, but instead include end of last image. After a few more swipe, the previous page could even take half of the screen. Any idea what could be the issue? Thanks.

example:

import SwiftUI

struct ContentView: View {
    var body: some View {
        GeometryReader { geometry in
            ScrollView(.horizontal) {
                LazyHStack {
                    ForEach(1...10, id: \.self) { _ in
                        Image(systemName: "rectangle.slash")
                            .frame(width: geometry.size.width)
                            .border(.red)
                    }
                }
                .scrollTargetLayout()
            }
            .scrollTargetBehavior(.paging)
        }
    }
}

#Preview {
    ContentView()
}

Screenshot, this is at page 5:

enter image description here

1

There are 1 answers

2
son On BEST ANSWER

It's because LazyHStack default spacing. Try this:

var body: some View {
    GeometryReader { geometry in
        ScrollView(.horizontal) {
            LazyHStack(spacing: 0) { //<- change spacing to 0
                ForEach(1...10, id: \.self) { _ in
                    Image(systemName: "rectangle.slash")
                        .frame(width: geometry.size.width)
                        .border(.red)
                }
            }
            .scrollTargetLayout()
        }
        .scrollTargetBehavior(.paging)
    }
}

Output

enter image description here