Are you using a UIPageControl? If so, this has a currentPage property. If not, I think you'll need to calculate the page index from the scrollView offset.
int indexOfPage = scrollView.contentOffset.x / scrollView.frame.size.width;
but if you use this code your view doesn't need to be exactly on the page that indexOfPage gives you.
It because I also recommend you to use this code only in this method
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
//MARK: - ScrollView Extensions
// Get the current page number
extension UIScrollView {
var currentPage: Int {
return Int(round(self.contentOffset.x / self.bounds.size.width))
}
// If you have reversed offset (start from contentSize.width to 0)
var reverseCurrentPage: Int {
return Int(round((contentSize.width - self.contentOffset.x) / self.bounds.size.width))-1
}
}
If Any one Looking for way of doing in C# for Xamarin
public int CurrentIndex
{
get => (int)Math.Round(this.scrollView.ContentOffset.X / this.scrollView.Frame.Width);
set => this.scrollView.ScrollRectToVisible(new CGRect(new CGPoint(this.scrollView.Frame.Size.Width * value, 0), this.scrollView.Frame.Size), true);
}
This getter and Setter should provide you current page as well let you scroll to the specified page