iOS6 UICollectionView and UIPageControl - How to get visible cell?

后端 未结 7 2080
甜味超标
甜味超标 2020-12-02 12:37

While studying iOS6 new features I got a question about UICollectionView.
I am currently testing it with Flow layout and the scroll direction set to horizontal, scrolli

7条回答
  •  抹茶落季
    2020-12-02 12:55

    I would recommend a little tuned calculation and handling as it will update page control immediately in any scroll position with better accuracy.

    The solution below works with any scroll view or it subclass (UITableView UICollectionView and others)

    in viewDidLoad method write this

    scrollView.delegate = self
    

    then use code for your language:

    Swift 3

    func scrollViewDidScroll(_ scrollView: UIScrollView) 
        {
           let pageWidth = scrollView.frame.width
           pageControl.currentPage = Int((scrollView.contentOffset.x + pageWidth / 2) / pageWidth)
        }
    

    Swift 2:

    func scrollViewDidScroll(scrollView: UIScrollView) 
    {
       let pageWidth = CGRectGetWidth(scrollView.frame)
       pageControl.currentPage = Int((scrollView.contentOffset.x + pageWidth / 2) / pageWidth)
    }
    

    Objective C

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView
    {
        CGFloat pageWidth = self.collectionView.frame.size.width;
        self.pageControl.currentPage = (self.collectionView.contentOffset.x + pageWidth / 2) / pageWidth;
    }
    

提交回复
热议问题