How do I create a horizontal scrolling UICollectionView in Swift?

user6520705 picture user6520705 · Oct 9, 2016 · Viewed 45.1k times · Source

How can I make a horizontal scrolling collectionView that fills up cells going across the rows rather than down the columns?

I want there to 5 columns and 3 rows but when there is more than 15 items I want it to scroll to the next page. I'm having a lot of trouble getting this going.

Answer

Ian Moses picture Ian Moses · Oct 9, 2016

Where you have a reference to your UICollectionViewFlowLayout(), just do:

layout.scrollDirection = .horizontal

Here is a nice tutorial for more info: https://www.youtube.com/watch?v=Ko9oNhlTwH0

Though for historical purposes, consider searching StackOverFlow quickly to make sure this isn't a duplicate.

Hope this helps.

Update: Your items will fill horizontally first and if there is not enough room within the collectionview going to the right, they will go to next row. So, start by increasing your collectionview.contentsize (should be larger the screen to enable scrolling) and then set your collectionview item (cell) size.

flowLayout.itemSize = CGSize(width: collectionView.contentSize.width/5, height: collectionView.contentSize.height/3)