I have been trying to achieve paging in swiftUI, which I pretty much achieved using two approaches. But the problem is that the paging Row is inside a vertical scroll. So, the gestures used for paging blocks the vertical scroll.
One of the approaches used for paging is below:
struct SwiftUIPagerView<Content: View & Identifiable>: View {
@Binding var index: Int
@State private var offset: CGFloat = 0
@State private var isGestureActive: Bool = false
// 1
var pages: [Content]
var body: some View {
GeometryReader { geometry in
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .center, spacing: 0) {
ForEach(self.pages) { page in
page
.frame(width: geometry.size.width, height: nil)
}
}
}
// 2
.content.offset(x: self.isGestureActive ? self.offset : -geometry.size.width * CGFloat(self.index))
// 3
.frame(width: geometry.size.width, height: nil, alignment: .leading)
.simultaneousGesture(DragGesture().onChanged({ value in
// 4
self.isGestureActive = true
// 5
self.offset = value.translation.width + -geometry.size.width * CGFloat(self.index)
}).onEnded({ value in
if -value.predictedEndTranslation.width > geometry.size.width / 2, self.index < self.pages.endIndex - 1 {
self.index += 1
}
if value.predictedEndTranslation.width > geometry.size.width / 2, self.index > 0 {
self.index -= 1
}
// 6
withAnimation { self.offset = -geometry.size.width * CGFloat(self.index) }
// 7
DispatchQueue.main.async { self.isGestureActive = false }
}))
}
}
}
Further, I use it like:
ScrollView(.vertical) {
SwiftUIPagerView(index: self.$activePageIndex, pages: (0..<4).map {
index in HomeBottleCard(bottle: DataSource.getBottles()[0])
})
SwiftUIPagerView(index: self.$activePageIndex, pages: (0..<4).map {
index in HomeBottleCard(bottle: DataSource.getBottles()[0])
})
}
Now the problem arises here. The Vertical scroll does not work. I have tried help from similar questions like Adding a drag gesture in SwiftUI to a View inside a ScrollView blocks the scrolling
But nothing helped. I would appreciate if anyone could come up with an idea to resolve this issue.