瀑布流网格

SwiftUI 的瀑布流网格布局视图。

Image Demo 1

特性

用法

初始化

您可以创建一个网格,通过传递您的数据集合和一个闭包来显示集合的元素,该闭包为集合中的每个元素提供一个视图。网格通过使用提供的闭包将集合中的每个元素转换为子视图。

WaterfallGrid 可以与可识别的数据一起使用(如 SwiftUI.List)。您可以通过两种方式使您的数据可识别:通过传递数据以及唯一标识每个元素的属性的键路径,或者通过使您的数据类型符合 Identifiable 协议。

示例 1

类型为 Image 的视图网格,来自通过键路径标识的数据集合。

WaterfallGrid((0..<10), id: \.self) { index in
  Image("image\(index)")
    .resizable()
    .aspectRatio(contentMode: .fit)
}

示例 2

类型为 RectangleView 的视图网格,来自 Identifiable 数据集合。

WaterfallGrid(rectangles) { rectangle in
  RectangleView(rectangle: rectangle)
}

或者,对于像这样的简单情况,只需

WaterfallGrid(rectangles, content: RectangleView.init)

网格样式

要自定义网格的外观,请调用 gridStyle 函数并传递您要自定义的参数。

WaterfallGrid(cards) { card in
  CardView(card: card)
}
.gridStyle(columns: 2)
WaterfallGrid(cards, content: CardView.init)
.gridStyle(
  columnsInPortrait: 2,
  columnsInLandscape: 3
)

间距和内边距

WaterfallGrid(rectangles, content: RectangleView.init)
.gridStyle(spacing: 8)
.padding(EdgeInsets(top: 16, leading: 8, bottom: 16, trailing: 8))

动画

WaterfallGrid(rectangles, content: RectangleView.init)
.gridStyle(animation: .easeInOut(duration: 0.5))

滚动行为

嵌入 ScrollView 和指示器选项

ScrollView(showsIndicators: true) {
  WaterfallGrid(rectangles, content: RectangleView.init)
}

水平滚动方向

ScrollView(.horizontal) {
  WaterfallGrid(rectangles, content: RectangleView.init)
  .scrollOptions(direction: .horizontal)
}

Animation Demo 4 Animation Demo 5

完整示例

ScrollView(.horizontal, showsIndicators: false) {
  WaterfallGrid(cards) { card in
    CardView(card: card)
  }
  .gridStyle(
    columnsInPortrait: 2,
    columnsInLandscape: 3,
    spacing: 8,
    animation: .easeInOut(duration: 0.5)
  )
  .scrollOptions(direction: .horizontal)
  .padding(EdgeInsets(top: 16, leading: 8, bottom: 16, trailing: 8))
}

示例应用

浏览 WaterfallGridSample 应用以获取更多详细和交互式示例。

Animation Demo 1  Animation Demo 2  Animation Demo 3

Image Demo 3

Image Demo 2

安装

Swift Package Manager

App 依赖

选择 File > Swift Packages > Add Package Dependency 并输入仓库 URL (Adding Package Dependencies to Your App)

Package 依赖

在您的 Package.swift 清单文件中将其添加为依赖项

dependencies: [
  .package(url: "https://github.com/paololeonardi/WaterfallGrid.git", from: "1.1.0")
]

CocoaPods

您可以通过将以下行添加到您的 Podfile 中,使用 CocoaPods 安装 WaterfallGrid

pod 'WaterfallGrid', '~> 1.1.0'

运行 pod install 命令以下载库并将其集成到您的 Xcode 项目中。

迁移指南

版本控制

有关可用版本,请参阅此仓库上的版本发布

贡献

非常欢迎贡献。请在提交拉取请求之前创建一个 GitHub issue 来计划和讨论实现。

作者

鸣谢

WaterfallGrid 的灵感来自以下项目

许可证

WaterfallGrid 在 MIT 许可证下可用。有关更多信息,请参阅 LICENSE 文件。