Skip to content

Instantly share code, notes, and snippets.

@zoejessica
Forked from mecid/PagerView.swift
Created December 26, 2019 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zoejessica/72c69e97db5d8bd6a0dbdde85eab12fc to your computer and use it in GitHub Desktop.
Save zoejessica/72c69e97db5d8bd6a0dbdde85eab12fc to your computer and use it in GitHub Desktop.
PagerView in SwiftUI
//
// PagerView.swift
//
// Created by Majid Jabrayilov on 12/5/19.
// Copyright © 2019 Majid Jabrayilov. All rights reserved.
//
import SwiftUI
struct PagerView<Content: View>: View {
let pageCount: Int
@Binding var currentIndex: Int
let content: Content
@GestureState private var translation: CGFloat = 0
init(pageCount: Int, currentIndex: Binding<Int>, @ViewBuilder content: () -> Content) {
self.pageCount = pageCount
self._currentIndex = currentIndex
self.content = content()
}
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)
.animation(.interactiveSpring())
.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)
}
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment