Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
}
)
}
}
}
@Plnda

This comment has been minimized.

Copy link

Plnda commented Jan 20, 2020

@mecid How would you solve animation on the pages? now when I have a animation set to a page the whole thing starts animating when I drag

@mecid

This comment has been minimized.

Copy link
Owner Author

mecid commented Jan 20, 2020

@mecid How would you solve animation on the pages? now when I have a animation set to a page the whole thing starts animating when I drag

I'm not sure I understand the problem, could you please describe it?

@Plnda

This comment has been minimized.

Copy link

Plnda commented Jan 20, 2020

@mecid

This comment has been minimized.

Copy link
Owner Author

mecid commented Jan 20, 2020

@majid Here is a sample + relevant code https://gist.github.com/Plnda/121b5960807074cf5fd68c68f959aa54

Interesting issue, you can add animation(nil) modifier to the content inside PagerView, I think it should help.

@Rep0se

This comment has been minimized.

Copy link

Rep0se commented Jan 22, 2020

@mecid A bug I noticed (which I've seen in some other apps) when you are switching between vertical scroll views diagonally, all objects will shift horizontally and remain that way until you scroll horizontally again to the next page. Is there a way to disable horizontal scrolling while you are scrolling vertically?
Also, what would change scroll sensitivity?
Edit: found another bug, where an image does not update until the end of the transition.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.