如何在swiftUI中制作特定的网格布局

问题描述 投票:0回答:1

如何在 swiftUI 中制作如下网格布局?

我尝试使用 LazyVStack 和 ZStack,但没有根据需要正确找到。

ios swift swiftui gridview grid
1个回答
0
投票

您可以使用一系列嵌套的

HStack
VStack
。通过
aspectRatio(1, contentMode: .fit)
将视图变成正方形。

struct ContentView: View {
    var body: some View {
        VStack {
            HStack {
                ForEach(0..<4) { _ in Square() }
            }
            HStack {
                VStack {
                    Square()
                    Square()
                }
                Square()
                VStack {
                    Square()
                    Square()
                }
            }
            HStack {
                ForEach(0..<4) { _ in Square() }
            }
        }
        .aspectRatio(1, contentMode: .fit)
        .padding()
    }
}

struct Square: View {
    var body: some View {
        Rectangle().stroke()
            .aspectRatio(1, contentMode: .fit)
    }
}

输出:

在您的屏幕截图中,正方形的垂直间距似乎比水平间距更大。这可以通过向

(spacing: ...)
VStack
添加不同的
HStack
参数来实现。

© www.soinside.com 2019 - 2024. All rights reserved.