2014-01-28 58 views
5

我使用以下代碼在水平方向對collection view進行分頁。我使用pageControl來表示我有多少頁和當前頁。無法獲得UICollectionView當前頁面

我使用類似於以下鏈接的方法來確定當前頁面。

iOS6 UICollectionView and UIPageControl - How to get visible cell?

UICollectionView: current index path for page control

正如以下。

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

但是,它不起作用。當我將collection view滑動到下一頁時,pageControl仍然指向第一頁。它不會改變它的價值。

我打印出self.collectionView.contentOffset.x的值,它總是在框架內(這是第一頁,即使我已經刷到下一頁),它永遠不會進入下一頁。

我做錯了什麼?

回答

5

您是否考慮了單元之間的間距?

試試這個:

-(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)); 
}