I know some people have asked this question before but they were all about UITableViews
or UIScrollViews
and I couldn't get the accepted solution to work for me. What I would like is the snapping effect when scrolling through my UICollectionView
horizontally - much like what happens in the iOS AppStore. iOS 9+ is my target build so please look at the UIKit changes before answering this.
Thanks.
This solution gives a better and smoother animation.
Swift 3
To get the first and last item to center add insets:
Then use the
targetContentOffset
in thescrollViewWillEndDragging
method to alter the ending position.Maybe in your case the
totalContentWidth
is calculated differently, f.e. without aminimumInteritemSpacing
, so adjust that accordingly. Also you can play around with the300
used in thevelocity
While originally I was using Objective-C, I since switched so Swift and the original accepted answer did not suffice.
I ended up creating a
UICollectionViewLayout
subclass which provides the best (imo) experience as opposed to the other functions which alter content offset or something similar when the user has stopped scrolling.For the most native feeling deceleration with the current layout subclass, make sure to set the following:
collectionView?.decelerationRate = UIScrollViewDecelerationRateFast
SWIFT 3 version of @Iowa15 reply
Needs to implement in UIScrollViewDelegate:
Here is a Swift 3.0 version, which should work for both horizontal and vertical directions based on Mark's suggestion above:
Here is my implementation
Implement your scroll view delegates like this
Also, for better snapping
Works like a charm
A modification of the above answer which you can also try: