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?
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));
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With