一个在 SwiftUI 上创建美观网格视图的简单方法 :)
此组件允许您将数组拆分为任意数量的列,同时仍然使用正确的索引处理原始数组。
https://github.com/thaisrfernandes/PinterestLikeGrid.git
该组件需要一个可哈希项目数组来显示,要使用的列数,以及一个闭包来表示网格中的每个项目。
这是一个如何使用它的示例
struct ContentView: View {
@State var data = [1, 2, 3, 4]
var body: some View {
PinterestLikeGrid($data, columns: 3, spacing: 8) { item, index in
Text("\(item)")
if let index = index {
Text("Index: \(index)")
}
}
}
}
参数 | 类型 | 描述 |
---|---|---|
data |
Binding<Array<T>> |
要在网格上显示的哈希项目绑定数组 |
columns |
Int |
(可选) 显示网格的列数。 默认为 2。 |
columnSpacing |
CGFloat |
(可选) 列之间的间距数。 默认为 8。 |
rowSpacing |
CGFloat |
(可选) 行之间的间距数。 默认为 8。 |
spacing |
CGFloat |
(可选) 行和列之间的间距数。 默认为 8。 |
content |
(_ item: T, _ index: Int) -> View |
接收一个项目和一个索引的闭包,该闭包必须返回一个视图来表示网格中的每个项目 |
PinterestLikeGrid($data) { item, index in
...
}
PinterestLikeGrid($data, columns: 3) { item, index in
...
}
PinterestLikeGrid($data, spacing: 12) { item, index in
...
}
PinterestLikeGrid($data, columns: 3, rowSpacing: 6) { item, index in
...
}
PinterestLikeGrid($data, columnSpacing: 3) { item, index in
...
}
PinterestLikeGrid 使用一个名为 splitData
的辅助方法将数据数组拆分为指定的列数。该方法返回一个哈希项目数组的数组。
然后,它使用 HStack
来显示列,并使用 VStack
来显示每列中的项目。
getIndexInList(for:)
是一个辅助方法,用于从数据数组中返回指定项目的索引。
此组件深受以下两个教程的启发,我对此表示特别感谢
Kavsoft - SwiftUI 3.0: Staggered Grid With Matched Geometry Effect - Xcode 13 - WWDC 2021