Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView horizontal paging with space between pages

I'm looking for a way to replace the native UIPageViewController horizontal paging with a UICollectionView.

so far i did the following:

let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.itemSize = collectionView.frame.size
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 10

collectionView.setCollectionViewLayout(layout, animated: false)
collectionView.isPagingEnabled = true
collectionView.alwaysBounceVertical = false

this works fine and i get an horizontal paging effect.

Now i want to add horizontal space between the pages (like u will do with UIPageViewControllerOptionInterPageSpacingKey on UIPageViewController)

so far i couldn't fine a way to add the spaces without damaging the paging effect. im looking for the same behavior as with the UIPageViewController: the cell should fill the entire screen width, and the space between the cells should only be visible when switching a page.

like image 207
Eyal Avatar asked Feb 27 '17 13:02

Eyal


People also ask

How do I make my UICollectionView scroll horizontal?

You need to reduce the height of UICollectionView to its cell / item height and select " Horizontal " from the " Scroll Direction " as seen in the screenshot below. Then it will scroll horizontally depending on the numberOfItems you have returned in its datasource implementation.

What is Uicollectionviewflowlayout?

A layout object that organizes items into a grid with optional header and footer views for each section.


1 Answers

Solution one:

  1. collectionView.isPagingEnabled = false
  2. add a minimumLineSpacing for the distance between pages
  3. implement targetContentOffsetForProposedContentOffset:withScrollingVelocity: to move the contentOffset to the closest page. You can calculate the page with simple math based on your itemSize and minimumLineSpacing, but it can take a little work to get it right.

Solution Two:

  1. collectionView.isPagingEnabled = true
  2. add a minimumLineSpacing for the distance between pages
  3. the paging size is based on the bounds of the collectionView. So make the collectionView larger then then screenSize. For example, if you have a minimumLineSpacing of 10 then set the frame of the collectionView to be {0,-5, width+10, height}
  4. set a contentInset equal to the minimumLineSpacing to make the first and last item appear correctly.
like image 94
Jon Rose Avatar answered Nov 15 '22 13:11

Jon Rose