Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Peek previous/next cells in UICollectionView with native paging enabled?

I want a collection view to page through cells and centered, but display a portion of the previous and next cells like this:

enter image description here

There are tons of hacks out there, but I'd like to achieve this with the native paging property of the UICollectionView. Making the cell the full width of the collection view doesn't show previous/next cells, and making the cell width smaller doesn't snap to center when paging.

Is is possible to make the collection view 80% of the screen width for example, and let the previous/next cells bleed outside the bounds (no clip to bounds)?

enter image description here

Or any other ideas to achieve this using the native paging?

like image 688
TruMan1 Avatar asked Oct 26 '25 18:10

TruMan1


1 Answers

iOS Swift 4

Use the below two methods to meek the previous and next screens.

private func calculateSectionInset() -> CGFloat {
    let deviceIsIpad = UIDevice.current.userInterfaceIdiom == .pad
    let deviceOrientationIsLandscape = UIDevice.current.orientation.isLandscape
    let cellBodyViewIsExpended = deviceIsIpad || deviceOrientationIsLandscape
    let cellBodyWidth: CGFloat = 236 + (cellBodyViewIsExpended ? 174 : 0)
    let buttonWidth: CGFloat = 50
    let inset = (collectionFlowLayout.collectionView!.frame.width - cellBodyWidth + buttonWidth) / 4
    return inset
}

private func configureCollectionViewLayoutItemSize() {
    let inset: CGFloat = calculateSectionInset() // This inset calculation is some magic so the next and the previous cells will peek from the sides. Don't worry about it
    collectionFlowLayout.sectionInset = UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset)
    collectionFlowLayout.itemSize = CGSize(width: collectionFlowLayout.collectionView!.frame.size.width - inset * 2, height: collectionFlowLayout.collectionView!.frame.size.height)
}

Don't forget to invoke configureCollectionViewLayoutItemSize() method in viewDidLayoutSubviews() of your UIViewController.

Screenshot

For more detailed reference Click Here

like image 161
Kartheek Avatar answered Oct 29 '25 07:10

Kartheek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!