Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not get UICollectionView current page

I paginated a collection view in horizontal direction, using the following code.

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.collectionView.pagingEnabled = YES;
    self.collectionView.directionalLockEnabled = YES;
    self.collectionView.bounces = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.delegate = self;

    [self setup];

    self.pageControl.currentPage = 0;

    self.pageControl.numberOfPages = floor(self.collectionView.contentSize.width /   self.collectionView.frame.size.width) + 1;
}

I am using pageControl to indicate the how many pages I have and the current page.

I used the method similar to the following links to determine the current page.

iOS6 UICollectionView and UIPageControl - How to get visible cell?

UICollectionView: current index path for page control

As following.

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger currentPage = self.collectionView.contentOffset.x / self.collectionView.frame.size.width;
    self.pageControl.currentPage = currentPage;
}

However, it does not work. When I swipe the collection view to next page, the pageControl still points to the very first page. It does not change its value.

I printed out the self.collectionView.contentOffset.x value, it always inside the frame (which is the first page, even I have swiped to the next page), it never goes to the next page.

Did I do something wrong?

like image 499
user890207 Avatar asked Jan 28 '14 07:01

user890207


2 Answers

Are you accounting for the spacing between cells?

Try this:

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    float currentPage = self.collectionView.contentOffset.x / self.collectionView.frame.size.width;
    self.pageControl.currentPage = ceil(currentPage);

    NSLog(@"Values: %f %f %f", self.collectionView.contentOffset.x, self.collectionView.frame.size.width, ceil(currentIndex));
}
like image 55
Joey Avatar answered Oct 03 '22 23:10

Joey


Swift 4.2 Page control get collection view current page

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

        let pageWidth = scrollView.frame.size.width
        currentPage = Int((scrollView.contentOffset.x + pageWidth / 2) / pageWidth)
        pageControl.currentPage = currentPage
    }
like image 42
Srinivasan_iOS Avatar answered Oct 03 '22 23:10

Srinivasan_iOS