Skip to content
A flexible grid layout view for SwiftUI
Branch: master
Clone or download
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.swiftpm/xcode Refactor Calculator Jul 8, 2019
Sources/GridStack Update for SwiftUI beta 4 Jul 18, 2019
Tests Add Calculator tests Jul 8, 2019
.gitignore Add file to .gitignore Jul 8, 2019
CODE_OF_CONDUCT.md Create CODE_OF_CONDUCT.md Jul 7, 2019
LICENSE Create LICENSE Jul 7, 2019
Package.swift Limit to iOS 13 and up Jul 7, 2019
README.md Update Readme to SwiftUI beta 4 syntax Jul 18, 2019

README.md

📱GridStack

A flexible grid layout view for SwiftUI.

Simply pass the minimum width the grid cells should have and the spacing between them and it will adjust depending on the available width.

So writing this:

GridStack(minCellWidth: 300, spacing: 2, numItems: 15) { index, cellWidth in
    Text("\(index)")
        .foregroundColor(.white)
        .frame(width: cellWidth, height: cellWidth * 0.66)
        .background(Color.blue)
}

will give you you this:

Screenshot 2019-07-14 at 14 07 02

It also adjusts correctly when the device is rotated:

rotation

🗺 Usage Overview

Think of the grid in the way of what is the minimum width you want your cells to be. That way it is easy to adjust to any available space. The only other size you need to provide is the spacing between the cells.

To actually create the grid we need to know the numbers of items. Then the content view builder will be called with each index and the cellWidth that you can then pass to the frame of whatever you want to display inside.

👕 Sizing your views inside the cells

The grid will wrap each item you provide with in a view that gets the cellWidth set as width. No height constraint is put on the cell. That is so that you can size your content as flexible as possible. Here are just a couple of examples what you can do.

Height defined by content

GridStack(...) { index, cellWidth in
    Text("\(index)")
        // Don't pass any height to the frame to let it be defined by it's content
        .frame(width: cellWidth)
}

Square items

GridStack(...) { index, cellWidth in
    Text("\(index)")
        // Pass the cellWidth as width and height to the frame to make a square
        .frame(width: cellWidth, height: cellWidth)
}

Aspect Ratio items

GridStack(...) { index, cellWidth in
    Text("\(index)")
        // Pass the cellWidth as width and a portion of it as height to get a certain aspect ratio
        .frame(width: cellWidth, height: cellWidth * 0.75)
}

✍️ Signature

GridStack(
    minCellWidth: Length,
    spacing: Length,
    numItems: Int,
    alignment: HorizontalAlignment = .leading,
    content: (index: Int, cellWidth: CGFloat) -> Void
)

📝 Mentions

I created GridStack by taking ideas from FlowStack by John Susek.

You can’t perform that action at this time.