我一直在尝试在swiftUI中实现分页,我几乎可以使用两种方法实现分页。但是问题是分页行在垂直滚动条内部。因此,用于分页的手势会阻止垂直滚动。
用于分页的一种方法如下:
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 }
}))
}
}
}
此外,我将其用作:
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])
})
}
现在问题出现了。垂直滚动不起作用。我尝试过类似Adding a drag gesture in SwiftUI to a View inside a ScrollView blocks the scrolling
这样的问题的帮助但是没有任何帮助。如果有人能提出解决此问题的想法,我将不胜感激。