我有一个 UICollectionView
,它上面有很多 UICollectionViewCells
。我想在点击时将单元格滚动到 UICollectionView
的中心。我担心的是,即使我点击最后一个或顶部的单元格,它也应该移动到 Collection View 的中心。
我已经尝试设置 contentInsets
和偏移量,但它们似乎不起作用。我想我必须在选择时更改内容大小,并在滚动开始时将其更改回原始大小。
最佳答案
设置 contentInsets 应该在第一个和最后一个单元格周围留出一些额外的空间:
CGFloat collectionViewHeight = CGRectGetHeight(collectionView.bounds);
[collectionView
setContentInset:
UIEdgeInsetsMake(collectionViewHeight/2, 0, collectionViewHeight/2, 0) ];
// nb, those are top-left-bottom-right
在你应该打电话之后:
[collectionView scrollToItemAtIndexPath:selectedItemPath
atScrollPosition:UICollectionViewScrollPositionCenteredVertically
animated:YES];
传递正确的滚动位置很重要:UICollectionViewScrollPositionCenteredVertically
这应该使点击的项目正确居中。
编辑
真的很奇怪,但是设置UIEdgeInsets到 Collection View 方法scrollToItemAtIndexPath后不能正常工作,所以我做了一些修改:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
CGFloat collectionViewHeight = CGRectGetHeight(self.collectionView.frame);
[collectionView setContentInset:UIEdgeInsetsMake(collectionViewHeight / 2, 0, collectionViewHeight / 2, 0)];
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
CGPoint offset = CGPointMake(0, cell.center.y - collectionViewHeight / 2);
[collectionView setContentOffset:offset animated:YES];
}
它对我来说很好。
关于ios - 点击时如何使 UICollectionView 居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17879533/