Getting the current page

2019-01-29 19:19发布

In my scroll view, I want to get the current page that's being displayed (maybe page isn't the correct term). I can't find any variable that holds this. But I think it must be held somewhere, since the indicator is able to show which sub-view of the scroll view is currently being displayed.

Is this hidden from us completely or is there a way for me to access it?

13条回答
Anthone
2楼-- · 2019-01-29 19:48

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
}
查看更多
登录 后发表回答