Skip to content

Instantly share code, notes, and snippets.

@FedeRotoli
Last active July 1, 2020 20:26
Show Gist options
  • Save FedeRotoli/dbe36a301c5bbb3a68e07219b6aa91e5 to your computer and use it in GitHub Desktop.
Save FedeRotoli/dbe36a301c5bbb3a68e07219b6aa91e5 to your computer and use it in GitHub Desktop.
struct PagerManager<Content: View>: View {
let pageCount: Int
@Binding var currentIndex: Int
let content: Content
//Set the initial values for the variables
init(pageCount: Int, currentIndex: Binding<Int>, @ViewBuilder content: () -> Content) {
self.pageCount = pageCount
self._currentIndex = currentIndex
self.content = content()
}
@GestureState private var translation: CGFloat = 0
//Set the animation
var body: some View {
GeometryReader { geometry in
HStack(spacing: 0) {
self.content.frame(width: geometry.size.width)
}
.frame(width: geometry.size.width, alignment: .leading)
.offset(x: -CGFloat(self.currentIndex) * geometry.size.width)
.offset(x: self.translation)
.gesture(
DragGesture().updating(self.$translation) { value, state, _ in
state = value.translation.width
}.onEnded { value in
let offset = value.translation.width / geometry.size.width
let newIndex = (CGFloat(self.currentIndex) - offset).rounded()
self.currentIndex = min(max(Int(newIndex), 0), self.pageCount - 1)
}
)
}
}
}
Copy link

ghost commented Jul 1, 2020

This is very cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment