How to Use A Writing Ritual to Get Into the Zone

By adding small actions to our daily routine, we can program our brains to better tackle our goals. S.J. Scott calls this habit stacking, which goes something like this: We can create a sequence of…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Equally Spaced UICollectionView Cells

A lot of apps tend to utilize Collection Views to organize information since it's a simple and effective way to display content to the user.

In this tutorial you will learn how to make a symmetrical Collection View where all cells have equal spacing between them.

First you should decide the space you want between the Collection View and the edge of the screen. This space can vary for each section if you need to.

This can be done both programatically and via Interface Builder.

If you like doing things the classic way, you can instantiate a Flow Layout, configure the Edge Insets and assign it to your Collection View, as shown below.

If you enjoy the practicality provided by Storyboards, you can edit the inset values in the Collection View object, on the size inspector tab.

Now we must assure that the cells have this same spacing between them. We can do this by using theUICollectionViewDelegateFlowLayout.

First, add the delegate to your CollectionViewController:

After that, we can call the sizeForItemAt method:

This method dictates the size for each cell in your Collection View and we can use it to calculate the exact size each cell should have to perfectly fit in the screen of any device the user is using.

For that, we are summoning the ancient powers of MATHEMATICS!

But it's really simple, seriously.

First, we must decide how many items our app will display on each row. How about 4 cells?

So, to display 4 cells with equal widths and the same amount of space between them we must first know how much horizontal space is going to be taken by the spacing. Then, we subtract this value from the total width of the collection view to obtain how much space is left to be divided by each cell.

With this implementation, you can easily edit the values to customize the Collection View the way you like best :D

Thanks for reading!

Add a comment

Related posts:

Introducing the WOM Token

Berlin is nothing if not a bundle of contradictions: The seat of the world’s most powerful export economy, it’s also an unabashed hub for outré hedonists. In recent years, however, these two…

How to Create a Healthy Workspace?

You know how hard our work can be, right? It’s important to prioritize self-care and ensure we’re taking care of our physical and mental well-being. That’s why I’ve put together this ultimate guide…