I have to develop a complex carousel in swift. It has to fulfill these requirements:
- Circular / Infinite loop.
- The cell in the middle of the view has to be bigger than the rest.
It should look like this:
My client prefers to use our own solution instead of using third party libraries.
So to achieve the first requirement (circular) I've implemented this solution:
Return a huge number of elements.
Use % operator to get the actual element.
Start showing the middle element of the collectionView.
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 1000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath, type: MyCollectionViewCell.self) as? MyCollectionViewCell, let element = elements[indexPath.row % totalSlides] cell.configure(element: element) return cell } return collectionView.dequeueReusableCell(withReuseIdentifier: "default", for: indexPath) }
This is working OK.
To achieve the second requirement (middle cell bigger) I've implemented this solution:
https://stackoverflow.com/a/61136150/1639825
Detect the middle cell and apply a scale transform to reduce the size of the rest of cells.
func updateCellsScale(centerX: CGFloat) {
for cell in collectionView.visibleCells {
cell.transform = CGAffineTransform.identity
var scaleX: CGFloat = 1.0
if centerX < cell.frame.origin.x || centerX > cell.frame.origin.x + cell.frame.size.width {
scaleX = 0.8
}
cell.transform = CGAffineTransform(scaleX: scaleX, y: scaleX)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let scrollOffsetX = scrollView.contentOffset.x
let scrollWidth = scrollView.bounds.size.width
let scrollHeight = scrollView.bounds.size.height
let centerPoint = CGPoint(x: scrollOffsetX + (scrollWidth / 2), y: scrollHeight / 2)
updateCellsScale(centerX: centerPoint.x)
}
But my client doesn't like this solution because the carousel looks like this:
Since I reduce the width and height scale to maintain the aspect ratio, the gap between cells is now bigger.
I've thought to increase the size of the middle cell instead of reduce the size of the other cells, but I would have this problem:
The middle cell will be over its left and right cells.
And I don't have more ideas of how to achieve this. I've searched for third party libraries too but I haven't found anyone that fulfills both requirements.
Any idea would be very appreciated.