Ios 无法获取UICollectionView当前页面

Ios 无法获取UICollectionView当前页面,ios,uicollectionview,Ios,Uicollectionview,我使用下面的代码在水平方向上对集合视图进行分页 - (void)viewDidLoad { [super viewDidLoad]; self.collectionView.pagingEnabled = YES; self.collectionView.directionalLockEnabled = YES; self.collectionView.bounces = NO; self.collectionView.showsHorizontalSc

我使用下面的代码在水平方向上对集合视图进行分页

- (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;
}
我正在使用
pageControl
指示我有多少页和当前页

我使用了类似于以下链接的方法来确定当前页面

如下

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger currentPage = self.collectionView.contentOffset.x / self.collectionView.frame.size.width;
    self.pageControl.currentPage = currentPage;
}
但是,它不起作用。当我将集合视图滑动到下一页时,
pageControl
仍然指向第一页。它不会改变它的值

我打印出了
self.collectionView.contentOffset.x
值,它总是在框架内(这是第一页,即使我已经刷到了下一页),它永远不会进入下一页


我做错什么了吗?

您是否考虑了单元格之间的间距

试试这个:

-(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 页面控件获取集合视图当前页面

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

        let pageWidth = scrollView.frame.size.width
        currentPage = Int((scrollView.contentOffset.x + pageWidth / 2) / pageWidth)
        pageControl.currentPage = currentPage
    }