如何在点击UICollectionView时将其居中?

Ank*_*ava 14 objective-c uiscrollview ios uicollectionview

我有一个UICollectionView,它有相当多的UICollectionViewCells东西.我想将单元格滚动到点击时的中心UICollectionView.我担心的是,即使我点击最后一个或顶部单元格,它也应该移动到集合视图的中心.

我尝试过设置contentInsets和偏移,但它们似乎不起作用.我想我必须在选择时更改内容大小,并在滚动开始时将其更改回原始大小.

Mik*_*ail 30

设置contentInsets应该在第一个和最后一个单元格周围留出一些额外空间:

CGFloat collectionViewHeight = CGRectGetHeight(collectionView.bounds);
[collectionView
  setContentInset:
   UIEdgeInsetsMake(collectionViewHeight/2, 0, collectionViewHeight/2, 0) ];
  // nb, those are top-left-bottom-right
Run Code Online (Sandbox Code Playgroud)

你打电话后:

[collectionView scrollToItemAtIndexPath:selectedItemPath
    atScrollPosition:UICollectionViewScrollPositionCenteredVertically
    animated:YES];
Run Code Online (Sandbox Code Playgroud)

传递正确的滚动位置非常重要: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];
}
Run Code Online (Sandbox Code Playgroud)

这对我来说可以.


bud*_*ino 12

Swift 3解决方案,用于滚动和居中屏幕,使点击的项目可见:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  collectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: true)
}
Run Code Online (Sandbox Code Playgroud)

这不会在上面或下面添加插页collectionView!


hum*_*ker 10

似乎这个错误是由滚动视图contentInset和 之间的错误交互引起的UICollectionViewFlowLayout.在我的测试中,设置layout.sectionInset而不是collectionView.contentInset消除问题.

基于上面接受的答案,我将消除变通方法,并更改:

[collectionView setContentInset:UIEdgeInsetsMake(collectionViewHeight / 2, 0, collectionViewHeight / 2, 0)];
Run Code Online (Sandbox Code Playgroud)

[layout setSectionInset:UIEdgeInsetsMake(collectionViewHeight / 2, 0, collectionViewHeight / 2, 0)];
Run Code Online (Sandbox Code Playgroud)