Is there a way to detect or get a notification when user changes the page in a paging-enabled UIScrollView?
It's not so easy to do this:
var quantumPage: Int = -100 { // the UNIQUELY LANDED ON, NEVER REPEATING page
didSet {
print(">>>>>> QUANTUM PAGE IS \(quantumPage)")
pageHasActuallyChanged() // your function
}
}
private var possibleQuantumPage: Int = -100 {
didSet {
if oldValue != possibleQuantumPage {
quantumPage = possibleQuantumPage
}
}
}
public func scrollViewDidEndDragging(
_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if decelerate == false {
possibleQuantumPage = currentPageEvenIfInBetween
}
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
possibleQuantumPage = currentPageEvenIfInBetween
}
var currentPageEvenIfInBetween: Int {
return Int((self.contentOffset.x + (0.5 * self.frame.width)) / self.frame.width)
}
Works perfectly.
pageHasActuallyChanged will only be called when the user changes pages in what humans would consider "changing pages".
This is difficult to initialize at bringup time, and will depend on how you are using the paged system.
In any paged system you will very likely have something like "scrollToViewAtIndex..."
open func scrollToViewAtIndexForBringup(_ index: Int) {
if index > -1 && index < childViews.count {
let w = self.frame.size.width
let h = self.frame.size.height
let frame = CGRect(x: CGFloat(index)*w, y: 0, width: w, height: h)
scrollRectToVisible(frame, animated: false) // NOTE THE FALSE
// AND IMPORTANTLY:
possibleQuantumPage = currentPageEvenIfInBetween
}
}
So, if the user opens the "book" at page 17, in your boss class you'd be calling that function to set it to "17" on bringup.
In such an example, you'd just have to remember that you must set initially our possibleQuantumPage value in any such bringup functions; there's no really generalized way to handle the starting situation.
After all you may, just for example, want to "quickly scroll" to the bringup page, and, who knows what that "means" in a quantumPage situation. So, be sure to initialize your quantum page system carefully during bringup, based on your situation.
In any event, just copy and paste the five functions at the top to get perfect quantum paging.