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

时间:2016-08-11 11:15:01

标签: ios swift uicollectionview uicollectionviewlayout

我正在尝试使用collectionView实现类似旋转木马的效果。我实施了UICollectionView并将其设置为显示水平单元格。

唯一的问题是如何只允许一个单元格出现并将该单元格置于屏幕中心。

注意:已启用分页。

我发现了这段代码,尝试了但遗憾的是没有用

代码参考:Create a Paging UICollectionView with Swift

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)
    }

1 个答案:

答案 0 :(得分:3)

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

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)
}