How to make a Waterfall UICollectionView using Swift

Last updated on: May 27, 2023

Today, I am going to show you how to add a waterfall layout in your UICollectionView, like Pinterest’s, quick and easy using CHTCollectionViewWaterfallLayout.

Pinterest’s CollectionView with Waterfall layout

First, we have to add CHTCollectionViewWaterfallLayout into our project.

Go to the Github page and download the repo:

..unzip it, copy the file CHTCollectionViewWaterfallLayout.swift and paste it into the project:

Add to your ViewController class who has the CollectionView the CHTCollectionViewDelegateWaterfallLayout delegate, set width and height for each item and the number of columns you want, like that:

extension CollectionView: CHTCollectionViewDelegateWaterfallLayout  {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let itemWidth = itemsArray[indexPath.row].width
        let itemHeight = itemsArray[indexPath.row].height
        return CGSize(width: itemWidth, height: itemHeight)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, columnCountFor section: Int) -> Int {
        return 2
    }
    
}Code language: Swift (swift)

…and lastly, set the CHTCollectionViewWaterfallLayout as layout into our CollectionView:

override func viewDidLoad() {
        super.viewDidLoad()
        //Other...
  
        // CollectionView Layout Setup
        setupCollectionViewLayout()
    }


func setupCollectionViewLayout() {

        // Create a waterfall layout
        let layout = CHTCollectionViewWaterfallLayout()

        // Change individual layout attributes for the spacing between cells
        layout.minimumColumnSpacing = 3.0
        layout.minimumInteritemSpacing = 3.0

        // Set the waterfall layout to your collection view
        self.collectionView.collectionViewLayout = layout
    }Code language: Swift (swift)

That’s it!

You can find the final project here

If you have any questionsplease feel free to leave a comment below

Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments