UICollectionView – 一次一个Cell的水平分页

我试图用collectionView来实现一个类似于效果的旋转木马。 我实现了UICollectionView并将其设置为水平显示单元格。

唯一的问题是我怎样才能允许一个单元格的外观,并将该单元格居中在屏幕上。

注意:寻呼已启用。

我发现这个代码,试了一下,但可悲的是没有工作

代码参考: 用Swift创build一个分页UICollectionView

 override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { if let cv = self.collectionView { let cvBounds = cv.bounds let halfWidth = cvBounds.size.width * 0.5; let proposedContentOffsetCenterX = proposedContentOffset.x + halfWidth; if let attributesForVisibleCells = self.layoutAttributesForElementsInRect(cvBounds) { var candidateAttributes : UICollectionViewLayoutAttributes? for attributes in attributesForVisibleCells { // == Skip comparison with non-cell items (headers and footers) == // if attributes.representedElementCategory != UICollectionElementCategory.Cell { continue } if let candAttrs = candidateAttributes { let a = attributes.center.x - proposedContentOffsetCenterX let b = candAttrs.center.x - proposedContentOffsetCenterX if fabsf(Float(a)) < fabsf(Float(b)) { candidateAttributes = attributes; } } else { // == First time in the loop == // candidateAttributes = attributes; continue; } } return CGPoint(x : candidateAttributes!.center.x - halfWidth, y : proposedContentOffset.y); } } // Fallback return super.targetContentOffsetForProposedContentOffset(proposedContentOffset) } 

以上代码的中心单元格是正确的,并且还实现了这两个方法:

 func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let currentIndex:CGFloat = self.GridCollectionView.contentOffset.x / self.GridCollectionView.frame.size.width pageControl.currentPage = Int(currentIndex) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSize(width: collectionView.frame.size.width, height: collectionView.frame.size.width+40) } 

如果项目的宽度是dynamic的,你可以尝试下面的代码

  - (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity { CGFloat offsetAdjustment = MAXFLOAT; CGFloat proposedHorizontalCenter = proposedContentOffset.x + (CGRectGetWidth(self.collectionView.bounds) / 2.0); CGRect targetRect = CGRectMake(proposedContentOffset.x, proposedContentOffset.y, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height); NSArray* array = [self layoutAttributesForElementsInRect:targetRect]; for (UICollectionViewLayoutAttributes* layoutAttributes in array) { CGFloat itemHorizontalCenter = layoutAttributes.center.x; if (ABS(itemHorizontalCenter - horizontalCenter) < ABS(offsetAdjustment)) { offsetAdjustment = itemHorizontalCenter - horizontalCenter; } } return CGPointMake(proposedContentOffset.x + offsetAdjustment, proposedContentOffset.y); }