重写scrollViewWillEndDragging时,UICollectionView并不总是为减速设置动画

3rd*_*Bot 4 paging custompaging uiscrollview ipad uicollectionview

我正在为我的UICollectionView创建自定义分页.我希望底部的一些单元格悬挂在屏幕边缘,但是,通过常规分页,滚动到下一页意味着如果页面底部的一半单元格显示,它将只显示另一半在下一页.我想让单元格悬挂在最后,但是停止分页,以便悬挂在屏幕上的单元格清晰可见.

所以,为了做到这一点,我覆盖了函数 - (void)scrollViewWillEndDragging:(UIScrollView*)scrollView withVelocity:(CGPoint)velocity targetContentOffset :( inout CGPoint*)targetContentOffset

如果我拖了一两秒钟,它看到按预期方式工作,但是,我想效仿"甩尾"的作品这么好启用分页时.当我轻弹我的UICollectionView时,它跳转到targetContentOffset,而不是动画到它.

我该如何防止这种情况?

这是我的代码:

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {

    if(targetContentOffset->y < 400) {
        targetContentOffset->y = 0;
        return;
    }

    int baseCheck = 400;

    while(baseCheck <= 10000) {
        if(targetContentOffset->y > baseCheck && targetContentOffset->y < baseCheck + 800) {
            targetContentOffset->y = (baseCheck + 340);
            return;
        }
        baseCheck += 800;
    }

    targetContentOffset->y = 0;
}
Run Code Online (Sandbox Code Playgroud)

bol*_*iva 6

我遇到了同样的问题,并成功地解决了这个问题.在我的例子中,我正在模拟一个分页的scrollView(实际上是一个UICollectionView),其中页面大小小于collectionView本身的大小.我注意到滚动的"跳跃"发生在一定条件下:

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    CGFloat pageWidth; // defined somewhere else
    NSInteger numberOfPages; // depends on your dataSource
    CGFloat proposedOffset = targetContentOffset->x;
    NSInteger currentPage = roundf(self.collectionView.contentOffset.x / pageWidth);
    NSInteger proposedPage = roundf(proposedOffset / pageWidth);
    // what follows is a fix for a weird case where the scroll 'jumps' into place with no animation
    if(currentPage == proposedPage) {
        if((currentPage == 0 && velocity.x > 0) ||
           (currentPage == (numberOfPages - 1) && velocity.x < 0) ||
           (currentPage > 0 && currentPage < (numberOfPages - 1) && fabs(velocity.x) > 0)
           ) {
            // this forces the scrolling animation to stop in its current place
            [self.collectionView setContentOffset:self.collectionView.contentOffset animated:NO];
            [UIView animateWithDuration:.3
                                  delay:0.
                                options:UIViewAnimationOptionCurveEaseOut
                             animations:^{
                                 [self.collectionView setContentOffset:CGPointMake(currentPage * pageWidth, 0)];
                             }
                             completion:NULL];
        }
    }
    targetContentOffset->x = (pageWidth * proposedPage);
}
Run Code Online (Sandbox Code Playgroud)