8
votes

I'm trying to implement a carousel like effect using collectionView. I implemented the UICollectionView and set it up to show cells horizontally.

The only problem is how can I allow the appearance of one cell only and to center that cell on the screen.

Note: Paging is enabled.

I found this code, tried it but sadly didn't work

Code reference : 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

1 Answers

4
votes

For center cell above code is right and also implement these two methods:

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