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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With