SwiftUI 实现网格布局

211 阅读1分钟

在使用 SwiftUI 开发时,我们可以使用 LazyVGrid 来实现垂直方向的网格布局;使用 LazyHGrid 来实现水平方向的网格布局。效果类似于 UIKitUICollectionView

代码示例如下:

class AppModel {
    var name = ""
    var imageBgColor = Color.red
    var id = UUID()
    
    init(name: String = "", imageBgColor: Color) {
        self.name = name
        self.imageBgColor = imageBgColor
    }
}

struct ContentView: View {
    let columns = [GridItem(.flexible()), GridItem(.flexible())]
    let dataSource = [AppModel(name: "应用1", imageBgColor: .purple),
                      AppModel(name: "应用2", imageBgColor: .blue),
                      AppModel(name: "应用3", imageBgColor: .green),
                      AppModel(name: "应用4", imageBgColor: .gray),
                      AppModel(name: "应用5", imageBgColor: .yellow)]
    
    var body: some View {
        ScrollView {
            LazyVGrid(columns: columns) {
                ForEach(dataSource, id: \.id) { value in
                    VStack(spacing: 10) {
                        Text(value.name)
                        Image("")
                            .frame(width: 60, height: 60)
                            .background(value.imageBgColor)
                    }
                }
            }
        }
    }
}

上述代码首先定义了一个 AppModel 的模型来组织数据。然后在 ContentView 中声明了一个 columns 的常量,它的元素数量代表了有几列。示例中有两个元素,所以会有两列。

接着定义了 dataSource 的常量来代表数据。

最后在 body 中,我们首先在外部用 ScrollView 来包裹,这表示我们的视图可以滑动。然后使用 LazyVGridcolumns 参数传递进去来创建垂直的网格视图。里面用 ForEach 来遍历数据源循环创建单元格。

单元格是纵向的,里面包含一个文本组件和图像组件。

效果图如下:

simulator_screenshot_0CC1D788-3514-42AC-98A5-BA97AA3D38D6.png

LazyHGrid 使用和 LazyVGrid 类似,区别只是一个是横向一个是纵向。