SwiftUI 网格视图布局,具有自定义样式。
打开 GridDemo.xcodeproj
以查看更多 iOS、macOS、watchOS 和 tvOS 示例
ScrollView {
Grid(colors) {
Rectangle()
.foregroundColor($0)
}
}
.gridStyle(
ModularGridStyle(columns: .min(100), rows: .fixed(100))
)
ScrollView {
Grid(1...69, id: \.self) { index in
Image("\(index)")
.resizable()
.scaledToFit()
}
}
.gridStyle(
StaggeredGridStyle(.horizontal, tracks: 8, spacing: 4)
)
轨道设置允许您自定义网格行为以适应您的特定用例。Modular 和 Staggered 网格都使用轨道值来计算布局。在 Modular 布局中,列和行都是轨道。
public enum Tracks: Hashable {
case count(Int)
case fixed(CGFloat)
case min(CGFloat)
}
网格被分割成父视图提供的等分大小。
ModularGridStyle(columns: 3, rows: 3)
StaggeredGridStyle(tracks: 8)
项目大小固定为特定的宽度或高度。
ModularGridStyle(columns: .fixed(100), rows: .fixed(100))
StaggeredGridStyle(tracks: .fixed(100))
自动布局,遵循最小项目宽度或高度。
ModularGridStyle(columns: .min(100), rows: .fixed(100))
StaggeredGridStyle(tracks: .min(100))
使用偏好设置获取项目大小和位置
struct CardsView: View {
@State var selection: Int = 0
var body: some View {
ScrollView {
Grid(0..<100) { number in
Card(title: "\(number)")
.onTapGesture {
self.selection = number
}
}
.padding()
.overlayPreferenceValue(GridItemBoundsPreferencesKey.self) { preferences in
RoundedRectangle(cornerRadius: 16)
.strokeBorder(lineWidth: 4)
.foregroundColor(.white)
.frame(
width: preferences[self.selection].width,
height: preferences[self.selection].height
)
.position(
x: preferences[self.selection].midX,
y: preferences[self.selection].midY
)
.animation(.linear)
}
}
}
}
欢迎通过 fork/pull request 向 master 分支贡献代码。如果您想请求新功能或报告错误,请创建一个新的 issue。
如果您觉得这个项目有用,请考虑成为我的 GitHub 赞助者。