Detect page change in UICollectionView

后端 未结 7 2107
醉酒成梦
醉酒成梦 2021-01-31 03:35

I tried finding this question for a while but could not find this problem\'s answer. My problem is that i have a UICollectionView and the Scroll Direction is

相关标签:
7条回答
  • 2021-01-31 03:44

    Use :

    - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
    {
        CGFloat pageWidth = collectionView.frame.size.width;
        float currentPage = collectionView.contentOffset.x / pageWidth;
    
        if (0.0f != fmodf(currentPage, 1.0f))
        {
            pageControl.currentPage = currentPage + 1;
        }
        else
        {
            pageControl.currentPage = currentPage;
        }
    
        NSLog(@"Page Number : %ld", (long)pageControl.currentPage);
    }
    

    And if you are not using any pageControl, then ceil(currentPage) will be your current page number.

    0 讨论(0)
  • 2021-01-31 03:46

    You can get the current page like below, index will be from 0 to (total page - 1)

    -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
     {
        CGFloat pageWidth = scrollView.frame.size.width;
        int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
        NSLog(@"Current page -> %d",page);
    }
    
    0 讨论(0)
  • 2021-01-31 03:55

    Swift 2.2

     func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        let x = collectionView.contentOffset.x
        let w = collectionView.bounds.size.width
        let currentPage = Int(ceil(x/w))
        print("Current Page: \(currentPage)")
    }
    
    0 讨论(0)
  • 2021-01-31 03:59

    Swift 3 Xcode 8.2

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
            let x = scrollView.contentOffset.x
            let w = scrollView.bounds.size.width
            let currentPage = Int(ceil(x/w))
            // Do whatever with currentPage.
    }
    
    0 讨论(0)
  • 2021-01-31 04:01

    Xamarin.iOS:

    You can override DecelerationEnded method of UICollectionViewDelegate or subscribe to DecelerationEnded event of UICollectionView (custom delegate will be used under the hood).

    public override void DecelerationEnded(UIScrollView scrollView)
    {
        var x = scrollView.ContentOffset.X;
        var w = scrollView.Bounds.Size.Width;
        var currentPage = Math.Ceiling(x / w);
    
        // use currentPage here
    }
    
    0 讨论(0)
  • 2021-01-31 04:05

    SWIFT 5

    For example, put this method in your ViewController with extensions UICollectionViewDelegate,UICollectionViewDataSource

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
            let pageWidth = scrollView.frame.size.width
            let page = Int(floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1)
            print("page = \(page)")
        }
    
    0 讨论(0)
提交回复
热议问题