# 3.4 格子（Grids）


<br>


# Grid

[Grid](https://developer.apple.com/documentation/swiftui/grid) 和 [GridRow](https://developer.apple.com/documentation/swiftui/gridrow) 是 iOS 16/macOS 13 新出的功能，用于快速构建静态格子视图。

一个 GridRow 对应的就是一行，Grid 可以设置 GridRow 中各列对其的方式以及横向和纵向的间距，具体效果可以参见示例。

<span style="background: #007BFF; color: white; padding: 3px 10px; border-radius: 5px">> 查看示例</span>

格子的对齐方式同时受到 Grid 和 GridRow 的 alignment 参数约束，SwiftUI 会先获取 Grid 的对齐方式对格子进行布局，如果 GridRow 也指定了对应行的 alignment，SwiftUI 会在 Grid 对齐方式的基础上叠加 GridRow 的对齐方式。

要使用空白格子进行占位，可以这样设置：

```swift
GridRow {
  // 空白占位格
  Color.clear
    .gridCellUnsizedAxes(.horizontal)
    .gridCellColumns(2)
  Rectangle()
    .fill(.green.gradient)
    .frame(width: 50, height: 50)
}
```

Color 是贪婪的，它会铺满一切可利用的空间，使用 `.gridCellUnsizedAxes` 方法可以阻止这一行为。而 `.gridCellColumns` 的作用是使对应的格子视图占据指定列数的空间，这在进行不规则布局时非常有用。

Grid 和嵌套 HStack 的 VStack 有点类似，但后者的每一行是独立的，无法灵活地对各列进行对齐，而 Grid 可以方便地在列方向上进行对齐操作，这是二者的显著区别。示例中的前两个彩色格子的样例已经作了清晰的展示，我们再回顾一下之前的 《布局的调整》 中关于“手机”和“电子邮箱”尾对齐的示例。此前我们是通过调整 alignmentGuide 来实现的，而使用 Grid 可以更加简单：

```swift
Grid(alignment: .trailing) {
  GridRow {
    Text("手机")
    Text("155********")
      .gridColumnAlignment(.leading)
  }
  GridRow {
    Text("电子邮箱")
    Text("xxxxxx@outlook.com")
  }
}
```

[gridColumnAlignment(_:)](https://developer.apple.com/documentation/swiftui/view/gridcolumnalignment(_:)) 用于指定 Grid 中某一列的对齐方式，它和 Grid 指定的 alignment 效果是叠加的，这和上文提到的 Grid 和 GridRow 的 alignment 会同时影响格子视图的布局是类似的。

此外，[gridCellAnchor(_:)](https://developer.apple.com/documentation/swiftui/view/gridcellanchor(_:)) 还可以改变格子视图的对齐锚点，官方文档已有详细示例，不再赘述。

# LazyHGrid、LazyVGrid

如果需要展示的数据量较大，使用 Grid 一次计算和渲染所有的视图会带来性能问题，此时就需要 [LazyHGrid](https://developer.apple.com/documentation/swiftui/lazyhgrid) 和 [LazyVGrid](https://developer.apple.com/documentation/swiftui/lazyvgrid) 了。二者的使用类似只是布局方向不同，它们都是嵌套在 ScrollView 中使用的，其核心要点是通过 [GridItem](https://developer.apple.com/documentation/swiftui/griditem) 进行动态布局。

每一个 GridItem 都对应格子视图中的某一行或列，我们可以对该行或列设置对齐方式（alignment）、间距（spacing）和尺寸（size）。

这里着重说一下 [GridItem.Size](https://developer.apple.com/documentation/swiftui/griditem/size-swift.enum)，它在 LazyHStack 中约束的是每个 item 的高度，其宽度默认自适应，除非指定具体值。在 LazyVStack 中则相反，它约束的是每个 item 的宽度。其实也很好理解，LazyHStack 是在水平方向上布局的，它要在有限高度内向水平方向上布局子视图，所以需要约束 item 的高度。而 LazyVStack 与此类似，只是方向不同罢了。

GridItem.Size 是一个枚举类型：

```swift
public enum Size {
				
	// 使用固定尺寸
	case fixed(CGFloat)

	// 指定最小或最大尺寸，默认最小尺寸为 10，最大为无限大
	case flexible(minimum: CGFloat = 10, maximum: CGFloat = .infinity)
  
  // 在可用的空间内生成尽可能多的自适应尺寸的 item，可以指定最小或最大尺寸
	case adaptive(minimum: CGFloat, maximum: CGFloat = .infinity)
}
```

理解了 GridItem 的作用，LazyHGrid、LazyVGrid 的使用就不在话下了，具体布局效果详见示例。






---

> 作者: 宋明  
> URL: https://apolla.cc/posts/3.4-%E6%A0%BC%E5%AD%90grids/  

