Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save moisesaq/e20672634e83fa7a4ced56932efb04a9 to your computer and use it in GitHub Desktop.
Save moisesaq/e20672634e83fa7a4ced56932efb04a9 to your computer and use it in GitHub Desktop.
[iOS]Select a item by scroll horizontal in a collection view
//------------------------------------- METHOD 1 ------------------------------------
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let index = Int(targetContentOffset.move().x / view.frame.width)
let indexPath = IndexPath(item: index, section: 0)
print("Current index path: \(indexPath.row)")
}
//------------------------------------- METHOD 2 ------------------------------------
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
var visibleRect = CGRect()
visibleRect.origin = collectionView.contentOffset
visibleRect.size = collectionView.bounds.size
let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
let indexPath = collectionView.indexPathForItem(at: visiblePoint)!
//guard let indexPath = visibleIndexPath else { return }
print("Current index path: \(indexPath.row)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment