Last active
October 21, 2016 08:43
-
-
Save michaelevensen/07a744cd1f98334ff58a1e40e227839d to your computer and use it in GitHub Desktop.
Slowly pages, not the snappy paging behavior but still nice.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
private let reuseIdentifier = "Cell" | |
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { | |
/* Return item size */ | |
var itemSize: CGSize { | |
let layout = self.collectionViewLayout as! UICollectionViewFlowLayout | |
return layout.itemSize | |
} | |
/* Return spacing: Interitem */ | |
var interItemSpacing: CGFloat { | |
let layout = self.collectionViewLayout as! UICollectionViewFlowLayout | |
return layout.minimumInteritemSpacing | |
} | |
/* Get section inset */ | |
var sectionInset: UIEdgeInsets { | |
let layout = self.collectionViewLayout as! UICollectionViewFlowLayout | |
return layout.sectionInset | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
} | |
// MARK: UICollectionViewDataSource | |
override func numberOfSections(in collectionView: UICollectionView) -> Int { | |
return 1 | |
} | |
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { | |
return 10 | |
} | |
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { | |
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) | |
return cell | |
} | |
/* Custom Paging */ | |
override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { | |
// Page size delta | |
let pagingDelta = floor(scrollView.contentOffset.x / self.itemSize.width) | |
// Spacing and Inset | |
let spacing = self.interItemSpacing - (self.sectionInset.left + self.sectionInset.right) | |
// Calculate offset depending on direction | |
let offset = (pagingDelta + ((velocity.x > 0) ? 1 : -1)) * (self.itemSize.width - spacing) | |
// Target point | |
let target = CGPoint(x: offset, y: 0) | |
targetContentOffset.pointee = target | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment