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.
Partly based on StevenOjo's answer. I've tested this using a horizontal scrolling and no Bounce UICollectionView. cellSize is CollectionViewCell size. You can tweak factor to modify scrolling sensitivity.
OK, so I found the solution here: targetContentOffsetForProposedContentOffset:withScrollingVelocity without subclassing UICollectionViewFlowLayout
I should have searched for
targetContentOffsetForProposedContentOffset
in the begining.Here is my version of it in Swift 3. Calculate the offset after scrolling ended and adjust the offset with animation.
collectionLayout
is aUICollectionViewFlowLayout()
Approach 1: Collection View
flowLayout
isUICollectionViewFlowLayout
propertyApproach 2: Page View Controller
You could use
UIPageViewController
if it meets your requirements, each page would have a separate view controller.Here's the easiest way that i found to do that in Swift 4.2 for horinzontal scroll:
I'm using the first cell on
visibleCells
and scrolling to then, if the first visible cell are showing less of the half of it's width i'm scrolling to the next one.If your collection scroll vertically, simply change
x
byy
andwidth
byheight
Yes, here's my implementation in Swift 4.1 for vertical cell-based paging:
This shouldn't glitch and allows you to set your own flickvelocity easily.
edit: Here's a horizontal version (haven't tested it thoroughly so please forgive any mistakes):