自定義UICollectionView橫向滑動分頁功能

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;
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容