ios - 点击时如何使 UICollectionView 居中?

标签 ios objective-c uiscrollview uicollectionview

我有一个 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/

相关文章:

ios - 现有应用在使用 Size Classes 时需要 UIScrollView

ios - 将 ScrollView 高度调整为屏幕高度?

ios - 如何在 ePub 阅读器中使用朗读屏幕自动打开页面

iOS 音频流仅适用于**某些**蓝牙设备?

ios - 在 swift 4 中循环提交 uitableviewcell

ios - 本地通知已安排,但不会以暂停和非运行模式发送

ios - 1080p AVCaptureSession

iphone - SLComposeViewController addURL 问题 iOS7

iphone - UIScrollView 内部 UIView 的 DrawRect

ios - 单击通用链接在我的应用程序中打开 WKWebView