48

I have successfully implemented a UICollectionView. Is it possible to change the scrollDirection?

Can you please show how to implement it programmatically?

LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
Entitize
  • 4,553
  • 3
  • 20
  • 28

3 Answers3

158

This is how you create it in code with UICollectionViewFlowLayout

let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
let collectionView = UICollectionView(frame: frame, collectionViewLayout: layout)

or if you are working with an existent collection view

if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
    layout.scrollDirection = .vertical
}
Jack
  • 13,571
  • 6
  • 76
  • 98
Sash Zats
  • 5,376
  • 2
  • 28
  • 42
  • 1
    When I tried to handle it in "viewWillTransition" method, its crashing: "Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value". What could be the reason? – Satyam Jun 14 '20 at 10:23
1

If you're using UICollectionViewCompositionalLayout

UICollectionViewCompositionalLayoutConfiguration has a scrollDirection property. Changing it will affect the whole collection view. You can also set separate scroll direction for each section if needed.

let configuration = UICollectionViewCompositionalLayoutConfiguration()
configuration.scrollDirection = .vertical

collectionView.collectionViewLayout = UICollectionViewCompositionalLayout(
    sectionProvider: { section, environment in
        // Return section
    },
    configuration: configuration
)
Senõr Ganso
  • 1,694
  • 16
  • 23
0

if you did not use storyboard and all is done with programmatically. so when we do that like this:

  lazy var snapCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let collectionView = UICollectionView(frame: CGRect.zero, 
        collectionViewLayout: layout)
        layout.scrollDirection = .horizontal
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor(named: "background")
        return collectionView
    }()
Muhammad Ahmad
  • 388
  • 4
  • 9