📱GridStack

一个用于 SwiftUI 的灵活网格布局视图。

WWDC20 更新

Apple  在 WWDC20 上发布了 LazyVGridLazyHGrid

如果你仅需支持 i(Pad)OS 14, macOS 11, tvOS 14, watchOS 7 或更高版本,那么 ^-- 绝对是你的首选。

如果你想支持 i(Pad)OS 13, macOS 10.15, tvOS 13, watchOS 6,请继续阅读。


Release Build & Test

📱 iOS 13+, 💻 macOS 10.15+, 📺 tvOS 13+, ⌚ watchOS 6+

只需传入网格单元格应具有的最小宽度和它们之间的间距,它将根据可用宽度自动调整。

所以像这样写

Code

将会得到这样的效果

Screenshot 2019-07-14 at 14 07 02

它在设备旋转时也能正确调整

rotation

🗺 使用概述

将网格视为你希望单元格具有的最小宽度。 这样可以轻松适应任何可用空间。 你需要提供的唯一另一个尺寸是单元格之间的间距

要实际创建网格,我们需要知道项目数量。 之后,内容 视图构建器将被调用,并为每个索引提供单元格宽度。 你可以将此宽度传递给你想要在单元格内显示的任何内容的 frame。

👕 调整单元格内视图的大小

网格会将你提供的每个项目包裹在一个视图中,该视图将 单元格宽度 设置为 宽度。 单元格上没有高度约束。 这样你就可以尽可能灵活地调整内容的大小。 这里有一些你可以做的示例。

高度由内容定义

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)
}

正方形项目

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)
}

宽高比项目

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)
}

✍️ 签名

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

📝 鸣谢

GridStack 的创建灵感来源于 FlowStack (作者:John Susek)。