There's some good answers here already. However, for scenarios where content doesn't fit exactly into a page - and if like me you want to use the result for a UIPageControl
, then it's essential to use the ceil
function.
Let's take an example where I have "four and a bit" pages of content.
I'll base this on my current real life example. The content size width is 3140 points. Based upon my collection view frame size, page width is 728.
So number of pages equals:
3140 / 728 = 4.313
My numberOfPages
is going to be five. Four of which will show in entirety, and the last of which - page five - will show that remaining 0.313
of content.
Now, numberOfPages
being five means that the page indices will be 0, 1, 2, 3, and 4.
When I swipe rightwards, paging towards the final offset, the scrollViewDidEndDecelerating
method gives a final X offset of 2412.
Applying the rounding calculation:
2412 / 728 = 3.313 then rounded = 3
That's incorrect. Page user is viewing by offset should be:
Offset / Page User Is Viewing
0 0
728 1
1456 2
2184 3
2412 4
The correct calculation using ceil
:
private func pageForOffset(offset:CGFloat, pageWidth width:CGFloat) -> Int
{
let page = Int(ceil(offset / width))
NSLog("\(__FUNCTION__) offset \(offset) width \(width) page \(page) ")
return page
}