1. pagingEnabled = true 可根據頁面寬度進行分頁
2. 自定義分頁功能
pagingEnabled一定要設為false
在scrollViewWillEndDragging:withVelocity:targetContentOffset:里自定義滑動方法
targetContentOffset 是個指針,可以修改這個參數的值,讓scrollView最終停止在目標位置。
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
float pageWidth = self.collectionView.width - 28*2 + 10; // width + space
float currentOffset = scrollView.contentOffset.x;
float targetOffset = targetContentOffset->x;
float newTargetOffset = 0;
if (targetOffset > currentOffset)
newTargetOffset = ceilf(currentOffset / pageWidth) * pageWidth;
else
newTargetOffset = floorf(currentOffset / pageWidth) * pageWidth;
if (newTargetOffset < 0)
newTargetOffset = 0;
else if (newTargetOffset > scrollView.contentSize.width)
newTargetOffset = scrollView.contentSize.width;
targetContentOffset->x = currentOffset;
[scrollView setContentOffset:CGPointMake(newTargetOffset, 0) animated:YES];
NSLog(F(@"%@",@(newTargetOffset)));
}
若為collectionView也可在UICollectionViewFlowLayout子類里重寫
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity;