得到了来自 SO 帖子 here 和文档 here 的答案
首先你可以做的是通过让你的类成为滚动视图委托来设置你的集合视图的滚动视图的委托你的类
MyViewController : SuperViewController<... ,UIScrollViewDelegate>
然后将您的视图控制器设置为委托
UIScrollView *scrollView = (UIScrollView *)super.self.collectionView;
scrollView.delegate = self;
或者在界面构建器中通过 control + shift 单击您的集合视图然后控制 + 拖动或右键单击拖动到您的视图控制器并选择委托。 (你应该知道如何做到这一点)。 这行不通。 UICollectionView 是 UIScrollView 的子类,因此您现在可以通过 control + shift 点击在界面构建器中看到它
接下来实现委托方法- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
MyViewController.m
...
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
}
文档声明:
参数
滚动视图 |正在减速滚动的滚动视图对象
的内容视图。
讨论 滚动视图在滚动时调用该方法
运动停止。 UIScrollView的减速属性
控制减速。
可用性适用于 iOS 2.0 及更高版本。
然后在该方法内部检查哪个单元格在停止滚动时最接近滚动视图的中心
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
//NSLog(@"%f", truncf(scrollView.contentOffset.x + (self.pictureCollectionView.bounds.size.width / 2)));
float visibleCenterPositionOfScrollView = scrollView.contentOffset.x + (self.pictureCollectionView.bounds.size.width / 2);
//NSLog(@"%f", truncf(visibleCenterPositionOfScrollView / imageArray.count));
NSInteger closestCellIndex;
for (id item in imageArray) {
// equation to use to figure out closest cell
// abs(visibleCenter - cellCenterX) <= (cellWidth + cellSpacing/2)
// Get cell width (and cell too)
UICollectionViewCell *cell = (UICollectionViewCell *)[self collectionView:self.pictureCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathWithIndex:[imageArray indexOfObject:item]]];
float cellWidth = cell.bounds.size.width;
float cellCenter = cell.frame.origin.x + cellWidth / 2;
float cellSpacing = [self collectionView:self.pictureCollectionView layout:self.pictureCollectionView.collectionViewLayout minimumInteritemSpacingForSectionAtIndex:[imageArray indexOfObject:item]];
// Now calculate closest cell
if (fabsf(visibleCenterPositionOfScrollView - cellCenter) <= (cellWidth + (cellSpacing / 2))) {
closestCellIndex = [imageArray indexOfObject:item];
break;
}
}
if (closestCellIndex != nil) {
[self.pictureCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathWithIndex:closestCellIndex] atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:YES];
// This code is untested. Might not work.
}