I'm new to Swift and iOS development, and am looking to set up a series of views, or "cards", that can be swiped left and right, with the next/previous cards remaining at the edges to indicate that they are there. This is done in iOS App Store previews:
So far all I've really found is this Medium article: iOS Swift: Swipe View. However I'm not sure if this is the right way to do what I'm asking above, and I also don't know how to get the next/previous cards to remain at the edges on each swipe.
Does anyone have any tips for achieving this?
The easiest way will be to use UICollectionView
and UICollectionViewFlowLayout
.
UICollectionViewFlowLayout
is provided out of the box and is very powerful.
Basically you need:
UICollectionView
to your view controller.UICollectionView
goes with Flow
layout selected.UICollectionViewFlowLayout
Steps above should be enough to have vertically scrollable cards view. But it will not look great! To make it great you probably need perfectly to center most appropriate card after user end scrolling. To achieve sticky scrolling you need to work with the following UICollectionViewDelegate
methods:
// compute collection view content offset in method bellow
override func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
...
}
// compute targetContentOffset in method bellow
override func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
...
}
... last hint: to make collection view deceleration look quick in code of your view controller do:
self.collectionView?.decelerationRate = UIScrollViewDecelerationRateFast
Paging indicator:
In example that you provide there is a paging control that reflects current item and overall items count. You need to add UIPageControll
manually; you can do it in storyboard. The best place to update page control state will be:
// method in UICollectionView delegate that you need to define.
// update your paging info in method bellow.
override func scrollViewDidScroll(scrollView: UIScrollView) {
...
}
Remarks:
Methods that deal with scroll view that i've listed are inherited by UICollectionViewDelegate
from UIScrollViewDelegate
. UICollectionView
itself derived from UIScrollViewDelegate
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With