Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save analogpotato/28fd835a3cf9c172f655ad3d14a5b960 to your computer and use it in GitHub Desktop.
Save analogpotato/28fd835a3cf9c172f655ad3d14a5b960 to your computer and use it in GitHub Desktop.
CollectionView horizontal scrolling example
//
//
//Here is the programmatic setup for the CollectionView
//
//
let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal //Change this to vertical
layout.minimumLineSpacing = 8 //Spacing here is not necessary, but adds a better inset for horizontal scrolling. Gives you a tiny peek of the background. Probably not great for vertical
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsets(top: 0, left: 4, bottom: 0, right: 4)
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.isPagingEnabled = true
collectionView.contentInsetAdjustmentBehavior = .never
collectionView.showsHorizontalScrollIndicator = false //Change this to vertical
collectionView.register(InspectionCardCollectionViewCell.self, forCellWithReuseIdentifier: InspectionCardCollectionViewCell.Constants.collectionIdentifier) //Register your own dang cell! lol
return collectionView
}()
//
//
//Create extension fo your scrollview delegate
//
//
extension ViewController : UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) { //When scrolling it sets the contentOffset to zero, so there is no offset when scrolling
collectionView.contentOffset.y = 0 //Set the offset to X for vertical maybe
}
}
//
//
//You may have to define a size for the view. Adding this here in the event you have trouble
//
//
extension ViewController: UICollectionViewDelegateFlowLayout { //Not sure if this is needed, I don't remember why I used it
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
let size = CGSize(width: collectionView.bounds.width - 8, height: collectionView.bounds.height)
return size
}
}
@parthp027
Copy link

This line saved my day. Thanks.

collectionView.contentInsetAdjustmentBehavior = .never

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment