获取当前页面

在我的滚动视图中,我想得到当前显示的页面(可能页面不是正确的术语)。我找不到任何保持这个的变量。但是我认为它必须放在某个地方,因为指示器能够显示当前显示的滚动视图的哪个子视图。

这东西是完全对我们隐藏起来了还是有办法让我进去?

70175 次浏览

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.

There is no UIScrollView property for the current page. You can calculate it with:

int page = scrollView.contentOffset.x / scrollView.frame.size.width;

If you want to round up or down to the nearest page, use:

CGFloat width = scrollView.frame.size.width;
NSInteger page = (scrollView.contentOffset.x + (0.5f * width)) / width;

Just divide the current offset by the page size:

CGFloat pageNum = (int)(scrollView.contentOffset.x / scrollView.frame.size.width);

The solution of Aoakenfo is amazing, this is another solution combining your code with the function scrollViewDidScroll and PageController

- (void)scrollViewDidScroll:(UIScrollView *)sender {
if (sender == self.scroll) {
int pageNum = (int)(self.scrPage.contentOffset.x / self.scrPage.frame.size.width);
self.pagecontroller.currentPage =pageNum;
}
}

As above but as a category


@interface UIScrollView (CurrentPage)
-(int) currentPage;
@end
@implementation UIScrollView (CurrentPage)
-(int) currentPage{
CGFloat pageWidth = self.frame.size.width;
return floor((self.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
}
@end

I extracted this out of a couple of our apps...

- (NSInteger)currentPage
{
if (0 == self.frame.size.width) {
NSLog(@"frame width == 0!");
return 0;
}
if (! self.currentPageValid) {
_currentPage = round(self.contentOffset.x / self.frame.size.width);
self.currentPageValid = YES;
}
return _currentPage;
}

Full source here

I pretty recommend you to use this code

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

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{}

which is called when your scrollView finishes scrolling and to have number of your page really sharp

I recommend you to set your scrollView to paged enabled with this code

[scrollView setPagingEnabled:YES];

So finally it should look like that way

-(void) methodWhereYouSetYourScrollView
{
//set scrollView
[scrollView setPagingEnabled:YES];
scrollView.delegate = self;
}


-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
int indexOfPage = scrollView.contentOffset.x / scrollView.frame.size.width;
//your stuff with index
}

In swift I would do it in extension:

extension UIScrollView {
var currentPage:Int{
return Int((self.contentOffset.x+(0.5*self.frame.size.width))/self.frame.width)+1
}
}

Then just call:

scrollView.currentPage

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
}

In xCode 7.x swift 2.x you can do :

//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
}
}

For swift I would just use this

    let width = scrollView.frame.width
let page = round(scrollView.contentOffset.x/width)

Pretty straightforward, it basically takes the scrollview x position, divides it by the scrollview width, then rounds it.

Another way:

extension MyViewController: UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let width = scrollView.frame.width
let page = Int(round(scrollView.contentOffset.x/width))
print("CurrentPage:\(page)")
}
}

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

Swift 5.1+ UIScrollView extension (Omitting the return keyword)

extension UIScrollView {


var currentPage: Int {
Int(round(self.contentOffset.x / self.frame.width))
}
}