UIScrollView delegate method scrollViewWillEndDragging: not



我正在尝试使用scrollViewWillEndDragging:方法来滚动我自己的分页UICollectionView,两侧都有类似于App Store应用程序的预览。但是,使用滚动视图下面的代码只会在没有惯性的情况下停止拖动(即只需抬起手指(滚动到所需的矩形。如果我以任何惯性轻拂该方法仍然被调用,但滚动视图不会滚动所需的矩形,它只是继续滚动?

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView
                     withVelocity:(CGPoint)velocity
              targetContentOffset:(inout CGPoint *)targetContentOffset
{
    int itemWidth = 280;
    MyCollectionView *collectionView = (MyIndexedCollectionView *) scrollView;
    int totalPages = [self.colorArray[collectionView.index] count];
    int currentPage;
    int nextPage;
    if (lastContentOffset < (int)scrollView.contentOffset.x)
    {
        // moved right
        NSLog(@"scrolling right");
        double currentPageOffset = ceil((scrollView.contentSize.width - 
                                                 scrollView.contentOffset.x) / itemWidth);
        currentPage = totalPages - currentPageOffset;
        nextPage = currentPage >= totalPages ? totalPages : currentPage + 1;
    }
    else if (lastContentOffset > (int)scrollView.contentOffset.x)
    {
        // moved left
        NSLog(@"scrolling left");
        double currentPageOffset = floor((scrollView.contentSize.width - 
                                              scrollView.contentOffset.x) / itemWidth);
        currentPage = totalPages - currentPageOffset;
        nextPage = currentPage <= 0 ? 0 : currentPage - 1;
    }
    int xOffset = (nextPage * itemWidth);
    int nextOffsetPage = (totalPages - ((scrollView.contentSize.width - xOffset) /
                                                                       itemWidth)) + 1;
    [scrollView scrollRectToVisible:CGRectMake(xOffset,
                                           0,
                                           collectionView.bounds.size.width,
                                           collectionView.bounds.size.height)
                                           animated:YES];
}

放弃此方法后,我尝试使用 scrollViewWillBeginDecelerating: 方法,完全相同的代码完美运行??我希望使用 scrollViewWillEndDragging: 方法的原因有两个:

  • 我想根据滚动的速度调整它跳转到的项目
  • 如果您通过抬起手指停止拖动而没有任何惯性,则不会调用 scrollViewWillBeginDecelerating: 方法。

任何想法,我是否误解了这个回调在做什么?

DOH!!事实证明,我应该使用targetContentOffset来设置我想滚动到的偏移量,而不是scrollToRectToVisible: ala:

*targetContentOffset = CGPointMake(myTargetOffset, targetContentOffset->y);

RTFM :)

最新更新