Collection View in SwiftUI

Cuneyt Zafer
SwiftUI Made Easy
Published in
2 min readJun 14, 2020
Photo by Karen Vardazaryan on Unsplash

Unfortunately, there is no collection view API in SwiftUI (yet?). However, by using VStack and Hstack we can create our own collection view wrapper.

If we were to write an API for collection view, we would at least need these:

private let data: [Data.Element]
private let numberOfColumns: Int
private let spacing: CGFloat
private let content: (Data.Element) -> Content

Hence, we we will initialize our view with these values.

init(_ data: Data,
numberOfColumns: Int = 2, // default is up to you
spacing: CGFloat = 8, // again here, the default value is up to your needs
content: @escaping (Data.Element) -> Content) {
self.data = data.map { $0 }
self.numberOfColumns = max(1, numberOfColumns)
self.spacing = spacing
self.content = content
self.numberOfRows = (data.count+numberOfColumns-1)/numberOfColumns
}

The rest is just laying out the view in body.

var body: some View {
VStack(spacing: spacing) {
ForEach(0..<numberOfRows) { rowIndex in
HStack(spacing: self.spacing) {
ForEach(0..<self.numberOfColumns) { columnIndex in
if
self.isValid(row: rowIndex, column: columnIndex) {
self.content(self.item(atRow: rowIndex, column: columnIndex))
}
}
}
}
}
}

We can improve this API by adding more customization such as vSpacing, hSpacing, a collection view header title etc.

Here is the full source code for this custom collection view:

I hope you enjoyed this article. Let me know if I missed anything or if you have anything to add to make the code better.

Happy coding!

--

--