Build Status

SwiftUI 网格

SwiftUI 网格视图布局,具有自定义样式。

功能

打开 GridDemo.xcodeproj 以查看更多 iOS、macOS、watchOS 和 tvOS 示例

样式

ModularGridStyle (默认)

ScrollView {
    Grid(colors) {
        Rectangle()
            .foregroundColor($0)
    }
}
.gridStyle(
    ModularGridStyle(columns: .min(100), rows: .fixed(100))
)

StaggeredGridStyle

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

SDK

路线图

代码贡献

欢迎通过 fork/pull request 向 master 分支贡献代码。如果您想请求新功能或报告错误,请创建一个新的 issue。

咖啡捐赠

如果您觉得这个项目有用,请考虑成为我的 GitHub 赞助者。