Spacing between collection view cells will be uneven without performing some simple math to calculate the correct size of the cells when including space. In this video, see what code must be added to create perfectly evenly spaced collection view cells.
- [Instructor] Let's look at giving our collection view cells equal amounts of space. So we have them uniform sizes, but we need to space them evenly. Let's head over into Xcode, and take a look at how that might work. So what we'll do is underneath the itemsPerRow constant, I'll define one called padding. And I'm going to have this be a CGFloat, and I'll set it equal to five. So five points of space, between each row and column.
Now, padding is something that's a little bit difficult to figure out, you have to do some math on it. The simple way to do it would be to subtract padding from the width, and then just a minimum interim spacing to padding, so that's the spacing between items, and the minimum line spacing to padding. If you run this, you might notice what's wrong. The spacing does look even, but watch what happens when I change the number of items per row to two for example.
When we set the number of items per row to two, there's a little bit more of an obvious difference in the spacing horizontally. Now, what's happening is, the width of each object is defined by it's padding. So, what we're seeing here is this object right here, number one, is half the width of the screen, minus our padding, which is five. The object on the right is also half the screen minus the width of the padding, which is five, and that gives us a total of 10 points of padding here, when what we really want is five.
You can see that, because it looks approximately double the size of the padding that we have vertically. So what we do to calculate the appropriate padding, is we figure out how much total padding we need, and then we divide that by the number of items that we have. Let's tab back over, and right under padding, we'll create another constant called totalPadding. And this is going to be padding times, and then in parentheses, itemsPerRow minus one.
And then on the next line, we can define individual padding as totalPadding divided by items per row. Then finally, instead of subtracting padding here when we define the width, we'll subtract individualPadding. With that, let's run the application and see what we get. When we run the app now, we get even padding.
At least we do with two objects. Let's try look at four objects per row. When you run the app again, you should still see even padding. And there we have it. So, if you want to create even spacing between your items, in a collection view, you can do it in this way.
- Alert controllers and actions
- Sliders, progress bars, and switches
- Creating UI elements with code
- Displaying web content with Safari view controllers and WKWebView
- Creating collection view controllers
- Creating tabbed apps
- Publishing your app with App Store Connect