Setting the Number of Columns in a CollectionView

Photo by Mauricio Artieda on Unsplash

With just a little bit of code you can control how many columns your collection view will display.

Here’s what to do:

First click on your collection view in the storyboard. Then click on the Size Inspector. Make sure that Estimate Size is set to None and that Section Insets are set to 0.

Next, in your view controller add an extension for the UICollectionViewDelegateFlowLayout.

Here you will specify how many columns you want, how much space in between each item and you can even change the number of columns when in landscape as opposed to portrait mode.

Depending whether your collection view cell is a perfect square or a rectangle, you can set the height based off of the width size. For example, if the height is 1 1/2 times taller than the width — in the itemSize constant set height to be itemWidth * 1.5

There is just one thing left to do. Add the function invalidateLayout() to your view controller. This invalidates the current layout and triggers a layout update. So when you rotate your device, the layout updates to fit the screen.

--

--

--

Web / iOS Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why your iOS apps keep crashing

Macbook shortcuts

On M1, Build iOS Simulator Test APP Got “…for architecture arm64” Error

ViewModels in Swift & Kotlin

Lambda School iOS Labs Project

UIDatePicker Date Change Listener : Swift

Modal presentation in iOS

Format On Save — Xcode / Swift

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kelly O’

Kelly O’

Web / iOS Developer

More from Medium

Get your weapon of choice with Swift

My first native iOS app: YOURA

100 Days of SwiftUI Learning — Day 3

App Tracking Transparency in iOS 15