There are already good answers there. However, for scenarios where the content does not match exactly on the page - and, like me, you want to use the result for UIPageControl , then it is important to use the ceil function.
Take an example where I have “four and several” content pages.
I will describe this using my real life as an example. The width of the content is 3140 pixels. Based on the frame size of the collection, the page width is 728.
Thus, the number of pages is:
3140 / 728 = 4.313
My numberOfPages will be five. Four of which will be displayed in full, and the last of which - page five - will show that there are 0.313 contents left.
Now numberOfPages means page indexes will be 0, 1, 2, 3, and 4.
When I scroll to the right, running to the final offset, the scrollViewDidEndDecelerating method gives the final offset of X 2412.
Application of rounding calculation:
2412 / 728 = 3.313 then rounded = 3
This is not true. The user viewing the page using offset should be:
Offset / Page User Is Viewing 0 0 728 1 1456 2 2184 3 2412 4
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 }
Max MacLeod Aug 20 '15 at 12:03 2015-08-20 12:03
source share