I have UICollectionView
with horizontal scrolling and there are always 2 cells side-by-side per the entire screen. I need the scrolling to stop at the begining of a cell. With paging enabled, the collection view scrolls the whole page, which is 2 cells at once, and then it stops.
I need to enable scrolling by a single cell, or scrolling by multiple cells with stopping at the edge of the cell.
I tried to subclass UICollectionViewFlowLayout
and to implement the method targetContentOffsetForProposedContentOffset
, but so far I was only able to break my collection view and it stopped scrolling. Is there any easier way to achieve this and how, or do I really need to implement all methods of UICollectionViewFlowLayout
subclass? Thanks.
Horizontal Paging With Custom Page Width (Swift 4)
Many solutions presented here result in some weird behaviour that doesn't feel like properly implemented paging.
The solution presented in this tutorial, however, doesn't seem to have any issues. It just feels like a perfectly working paging algorithm. You can implement it in 5 simple steps:
private var indexOfCellBeforeDragging = 0
collectionView
delegate
like this:collectionView.delegate = self
UICollectionViewDelegate
via an extension:extension YourType: UICollectionViewDelegate { }
Add the following method to the extension implementing the
UICollectionViewDelegate
conformance and set a value forpageWidth
:Add the following method to the extension implementing the
UICollectionViewDelegate
conformance, set the same value forpageWidth
(you may also store this value at a central place) and set a value forcollectionViewItemCount
:Kind of like evya's answer, but a little smoother because it doesn't set the targetContentOffset to zero.
This is a straight way to do this.
The case is simple, but finally quite common ( typical thumbnails scroller with fixed cell size and fixed gap between cells )
Note that there is no reason to call a scrollToOffset or dive into layouts. The native scrolling behaviour already does everything.
Cheers All :)
Here is my way to do it by using a
UICollectionViewFlowLayout
to override thetargetContentOffset
:(Although in the end, I end up not using this and use UIPageViewController instead.)
Also you can create fake scroll view to handle scrolling.
Horizontal or Vertical
just override the method: