我正在为我的 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;
}
我遇到了同样的问题并设法解决了它。在我的例子中,我模拟一个分页的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);
}
它直接“跳转”到 targetContentOffset,因为它使用给定的速度。 而且轻弹的速度非常高。 你应该检查速度的值,如果优于某个速率(我认为大约 2,但你可以调整),那么你自己做动画(用一个简单的
[scrollView setContentOffset:contentOffset animated:YES];