Setting the Number of Columns in a CollectionView

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.

--

--

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