Entitize
Entitize

Reputation: 4969

How to change UICollectionView Scroll Direction?

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

Can you please show how to implement it programmatically?

Upvotes: 50

Views: 61354

Answers (3)

Senõr Ganso
Senõr Ganso

Reputation: 1734

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
)

Upvotes: 2

Muhammad Ahmad
Muhammad Ahmad

Reputation: 398

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
    }()

Upvotes: 1

Sash Zats
Sash Zats

Reputation: 5466

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
}

Upvotes: 162

Related Questions