Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 599
Doraemoe Avatar asked Oct 18 '25 19:10

Doraemoe


1 Answers

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

like image 189
sonle Avatar answered Oct 21 '25 09:10

sonle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!