Is there a way to detect or get a notification when user changes the page in a paging-enabled UIScrollView?
Swift 4
I found the best way to do this is by using scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)
. It lets you predict if paging will occur as soon as you lift your finger off the screen. This example is for paging horizontally.
Remember to the assign the scrollView.delegate
to the object that adopts UIScrollViewDelegate
and implements this method.
var previousPageXOffset: CGFloat = 0.0
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) {
let targetOffset = targetContentOffset.pointee
if targetOffset.x == previousPageXOffset {
// page will not change
} else if targetOffset.x < previousPageXOffset {
// scroll view will page left
} else if targetOffset.x > previousPageXOffset {
// scroll view will page right
}
previousPageXOffset = targetOffset.x
// If you want to track the index of the page you are on just just divide the previousPageXOffset by the scrollView width.
// let index = Int(previousPageXOffset / scrollView.frame.width)
}