CollectionView 按单元分页 不按frame 分页

310 阅读1分钟

0A_GX6T3z7E.png

重写scrollViewWillEndDragging 方法即可,计算你想要滑动的距离然后赋值给offset,

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    *targetContentOffset = scrollView.contentOffset; // set acceleration to 0.0
    CGFloat pageWidth = (SCREEN_W - 19*2 - 53);

    NSInteger cellToSwipe = (scrollView.contentOffset.x)/(pageWidth); // cell width + min spacing for lines
    CGFloat   cellIndex = (scrollView.contentOffset.x)/(pageWidth);
    cellIndex = roundf(cellIndex);

    CGFloat scrollOffset = pageWidth * cellIndex + 19*cellIndex;
    CGPoint scrollPoint = CGPointMake(scrollOffset, 0);
    [self.dataCollection setContentOffset:scrollPoint animated:YES];
}