UICollectionView与分页启用

我必须像Appstore iOS应用程序一样创build网格视图。 我想用UICollectionView分页来做到这一点。 我也实现了代码,但不能像这样滚动。

我想要做的是在中心和左右两边都会有一个图像,它应该显示上一张和下一张图像的一部分。 我为UICollectionView设置了Frame为320 * 320。 单元尺寸为290 * 320(单元最小间距为10)

以下是描述我的要求的两个链接。 提前致谢。

(这是我想要的) 2

你有没有尝试将UICollectionViewFlowLayout的滚动方向设置为水平?

[yourFlowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];

您需要在集合视图上启用分页,如下所示:

[yourCollectionView setPagingEnabled:YES];

我采取了shtefane的答案和改进。 input您自己的cellWidthcellPadding值。

 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset { CGFloat cellWidth = self.cellWidth; CGFloat cellPadding = 9; NSInteger page = (scrollView.contentOffset.x - cellWidth / 2) / (cellWidth + cellPadding) + 1; if (velocity.x > 0) page++; if (velocity.x < 0) page--; page = MAX(page,0); CGFloat newOffset = page * (cellWidth + cellPadding); targetContentOffset->x = newOffset; } 

如果您在collectionView中使用pagining,则它将滚动一个页面不是一个单元格。 你可以禁用分页和实现ScrollViewDelegate

 - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset { CGFloat pageW = 300; int page = scrollView.contentOffset.x / pageW; CGFloat newOffset =(page + ((velocity.x > 0)? 1 : -1)) * (pageW - 20); CGPoint target = CGPointMake(newOffset, 0); targetContentOffset = &target; NSLog(@"end Drag at %f /%i /%f",scrollView.contentOffset.x, page, velocity.x); } 

只有一个不同于标准分页:如果您快速拖动集合将滚动多个单元格。 别忘了添加UIScrollViewDelegate

参考Rickster的答案,我用Swift 4重写:

 /* paging */ extension AlbumViewController { /* In case the user scrolls for a long swipe, the scroll view should animate to the nearest page when the scrollview decelerated. */ override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollToPage(scrollView, withVelocity: CGPoint(x:0, y:0)) } override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { scrollToPage(scrollView, withVelocity: velocity) } func scrollToPage(_ scrollView: UIScrollView, withVelocity velocity: CGPoint) { let cellWidth: CGFloat = cellSize let cellPadding: CGFloat = 10 var page: Int = Int((scrollView.contentOffset.x - cellWidth / 2) / (cellWidth + cellPadding) + 1) if velocity.x > 0 { page += 1 } if velocity.x < 0 { page -= 1 } page = max(page, 0) let newOffset: CGFloat = CGFloat(page) * (cellWidth + cellPadding) scrollView.setContentOffset(CGPoint(x:newOffset, y:0), animated: true) } }