检测UICollectionView中的页面更改

Ahs*_*him 28 iphone objective-c ios ios8

我尝试了一段时间找到这个问题,但找不到这个问题的答案.我的问题是我有一个UICollectionView和滚动方向Horizontal一起Paging Enabled.我的问题是我想要保持用户所在的当前页码的大头钉,所以我创建了一个int变量,现在每次用户向右或向左滑动时都要加1或减去它.我尝试过使用scrollView代表

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
Run Code Online (Sandbox Code Playgroud)

但是当用户向右或向左滑动时,它被称为多次,因为页面上的列数UICollectionView加上它不会让我知道用户是去了下一页还是前一页.

its*_*dra 40

使用 :

- (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);
}
Run Code Online (Sandbox Code Playgroud)

如果您没有使用任何pageControl,那么ceil(currentPage)将是您当前的页码.


Ahm*_*adi 38

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.
}
Run Code Online (Sandbox Code Playgroud)


And*_*rej 10

根据@Shankar BS的回答,我在Swit中实现了这个.请记住,CollectionViewDelegate符合ScrollViewDelegate:

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let pageWidth = scrollView.frame.size.width
    let page = Int(floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1)
    print("page = \(page)")
}
Run Code Online (Sandbox Code Playgroud)


Sha*_* BS 8

你可以像下面的当前页面,指数将来自0(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);
}
Run Code Online (Sandbox Code Playgroud)


Álv*_*ero 7

快速 5

例如,将此方法放在带有扩展 UICollectionViewDelegate,UICollectionViewDataSource 的 ViewController 中

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let pageWidth = scrollView.frame.size.width
        let page = Int(floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1)
        print("page = \(page)")
    }
Run Code Online (Sandbox Code Playgroud)