如何在点击UICollectionView时将其居中?
我有一个UICollectionView
,它上面有很多UICollectionViewCells
。 我想在UICollectionView
时将单元格滚动到UICollectionView
的中心。 我担心的是,即使我点击最后一个或顶部单元格,它也应该移动到集合视图的中心。
我已经尝试设置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设置为集合视图方法后,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]; }
这对我来说可以。
看来这个错误是由滚动视图的contentInset
和UICollectionViewFlowLayout
之间的错误交互引起的。 在我的测试中,设置layout.sectionInset
而不是collectionView.contentInset
消除了这个问题。
基于上面接受的答案,我将消除变通方法,并更改:
[collectionView setContentInset:UIEdgeInsetsMake(collectionViewHeight / 2, 0, collectionViewHeight / 2, 0)];
至
[layout setSectionInset:UIEdgeInsetsMake(collectionViewHeight / 2, 0, collectionViewHeight / 2, 0)];
Swift 3解决方案,用于滚动和居中屏幕,使点击的项目可见:
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: true) }
这不会在collectionView
上面或下面添加插页!
您可以使用scrollToItemAtIndexPath
方法将选定(点击)的单元格置于UICollectionView中的中心位置
[collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:true];
您可以将UICollectionViewScrollPositionCenteredVertically
用于垂直居中位置